<template>
  <div class="p-4">
    <a-button v-if="isAdd" type="primary" @click="addRow"> 新增 </a-button>
    <BasicTable @register="registerTable" :dataSource="dataSource" @edit-change="onEditChange">
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
      <template #bodyCell="{ record, column, index }">
        <div v-if="record.editable && column.dataIndex === 'link_devicetype_text'">
          <ApiTreeSelect
            style="width: 100%"
            :api="deviceList.bind(null, { devicetype: '' })"
            :fieldNames="{ children: 'children', label: 'itemText', value: 'itemValue' }"
            @change="handleChangeDeviceType($event, index)"
            v-model:value="record['editValueRefs']['link_devicetype']"
            placeholder="请选择设备分类"
          />
        </div>
        <div v-if="record.editable && column.dataIndex === 'link_id_text'">
          <Select
            show-search
            :default-active-first-option="false"
            :filter-option="filterOption"
            @change="handleChange($event, index)"
            :options="options"
            :fieldNames="{ label: 'deviceName', value: 'deviceID' }"
            v-model:value="record['editValueRefs']['link_id']"
            style="width: 100%"
          />
        </div>
        <div v-if="record.editable && column.dataIndex === 'link_code'">
          <Select
            style="width: 100%"
            :options="monitorParamsOptions"
            :fieldNames="{ label: 'valuename', value: 'valuecode' }"
            @change="handleChangeLinkCode($event, index)"
            v-model:value="record['editValueRefs']['link_code']"
            :virtual="false"
          />
        </div>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, inject, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, ActionItem, EditRecordRow } from '/@/components/Table';
  import { Select } from 'ant-design-vue';
  import { ApiTreeSelect } from '/@/components/Form';
  import { deviceId, getDeviceId, deviceList, list, pointEdit } from './point.api';
  // import { nextTick } from 'process';

  export default defineComponent({
    components: { BasicTable, TableAction, Select, ApiTreeSelect },
    props: {
      columns: {
        type: Array,
        requried: true,
      },
      deviceId: {
        type: String || Number,
        requried: true,
      },
      valuetype: {
        type: Number,
        requried: true,
      },
      pointType: {
        type: String,
        requried: true,
      },
      list: {
        type: Function,
        requried: true,
      },
      isAdd: {
        type: Boolean,
      },
    },
    emits: ['save', 'delete'],
    setup(props, { emit }) {
      const deviceType = inject('deviceType');
      const options = ref([]);
      const monitorParamsOptions = ref([]);
      const currentEditKeyRef = ref('');
      const dataSource = ref<any>([]);
      const [registerTable, { insertTableDataRecord, reload }] = useTable({
        title: '',
        columns: props.columns as BasicColumn[],
        showIndexColumn: false,
        showTableSetting: false,
        tableSetting: { fullScreen: true },
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      const filterOption = (input: string, option: any) => {
        return option.deviceName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      };
      function addRow() {
        const record = {} as EditRecordRow;
        insertTableDataRecord(record);
        nextTick(() => {
          handleEdit(record);
        });
      }
      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.key;
        record.onEdit?.(true);
        handleChange(record['link_id']);
        handleChangeDeviceType(record['link_devicetype']);
      }

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

      function handleDelete(record: EditRecordRow) {
        emit('delete', record.id, reload);
      }
      function getOptions(value) {
        console.log(value);
      }

      function handleChange(id, index?) {
        if (!id) return;
        if (index !== undefined) dataSource['value'][index]['link_id'] = id;

        deviceId({ id: id }).then((res) => {
          monitorParamsOptions.value = res;
          console.log(res);
        });
      }
      function handleSearch(val: string) {
        return options.value.map((item) => {
          return (item['deviceName'] as string).includes(val);
        });
      }

      function handleChangeDeviceType(e, index?) {
        if (!e) return;
        if (index !== undefined) dataSource['value'][index]['link_devicetype'] = e;
        getDeviceId({ devicetype: e }).then((res) => {
          options.value = res;
        });
      }

      function handleChangeLinkCode(e, index?) {
        if (!e) return;
        if (index !== undefined) dataSource['value'][index]['link_code'] = e;
      }

      async function handleSave(record: EditRecordRow) {
        dataSource.value.filter((item) => {
          if (record.id && record.id === item.id) {
            console.log(111);
            Object.assign(item, record.editValueRefs);
            item['test'] = '1212';
            console.log(222, item, record.editValueRefs);
          }
        });
        // await edit(dataSource.value);
        await pointEdit({ deviceid: props.deviceId, linklist: dataSource.value });
        currentEditKeyRef.value = '';
        record.onEdit?.(false, false);
        await getDataSource(props.pointType);
      }

      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),
              },
            ];
          }
        }
        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);
      }

      // watch(() => props.pointType, async(pointType) => {
      //   await getDataSource(pointType)
      // })

      async function getDataSource(pointType) {
        const result = await list({ devicetype: pointType, valuetype: props.valuetype, deviceid: props.deviceId });
        dataSource.value = result.records;
      }
      onMounted(async () => {
        await getDataSource(props.pointType);
      });

      return {
        registerTable,
        handleEdit,
        createActions,
        onEditChange,
        addRow,
        handleChange,
        handleSearch,
        handleChangeDeviceType,
        handleChangeLinkCode,
        getOptions,
        options,
        monitorParamsOptions,
        deviceList,
        dataSource,
        filterOption,
      };
    },
  });
</script>
<style scoped lang="less">
  @ventSpace: zxm;
  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
  }
  .@{ventSpace}-dropdown-menu-item {
    color: black;
  }
</style>
