<template>
  <ns-drawer
    v-model:visible="visible"
    width="520"
    title=" "
    :ok="btnClick"
    :cancel="() => (visible = false)"
    placement="right">
    <ns-form
      ref="editGroupRef"
      :schemas="schemas(inputDisabled)"
      :model="model"
      formLayout="vertical"
      :wrapperCol="{ span: 20 }"
      :labelCol="{ span: 4 }">
      <template #addonAfter="data">
        <template v-if="data.field === 'groupName'">
          <div class="iconOP">
            <EditOutlined title="编辑" v-if="inputDisabled" @click="editGroup" />
            <CheckOutlined title="保存" v-else @click="add" />
          </div>
        </template>
      </template>
    </ns-form>
    <div
      style="
        font-size: 16px;
        font-weight: bold;
        line-height: 24px;
        padding: 16px 0;
        padding-top: 0;
      ">
      分组列表
      <ns-button style="margin-left: 10px" type="primary" @click="addGroup">新增</ns-button>
    </div>
    <NsBasicTable
      v-model:dataSource="mockDataSource"
      v-bind="basicTableConfig"
      :rowSelection="{
        type: 'radio',
        onChange: rowSelectChange,
        selectedRowKeys,
      }" />
  </ns-drawer>
</template>
<script lang="ts" setup>
  import { createVNode, onMounted, ref, unref } from 'vue';
  import { NsMessage } from '/nerv-lib/component';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import { group } from '/@/api/deviceManage';
  import { http } from '/nerv-lib/util/http';
  import { EditOutlined, CheckOutlined } from '@ant-design/icons-vue';
  import { Popconfirm } from 'ant-design-vue';
  const emit = defineEmits(['sure']);
  const props = defineProps({ params: Object });
  const visible = ref(false);
  const editGroupRef = ref();
  const model = ref({});
  const inputDisabled = ref(true);
  const selectedRowKeys = ref([]);
  let opType = true; // true新增false编辑
  const toggle = () => {
    visible.value = !visible.value;
    visible.value && getTableData();
  };

  const startCararcter = 65;
  // 点击新增按钮新增分组
  const addGroup = () => {
    opType = true;
    getCode();
    const code = startCararcter + mockDataSource.value?.length;
    inputDisabled.value = false;
    model.value = { groupName: '' };
    // if(mockDataSource.value.length)
  };

  const op = () => {
    inputDisabled.value = !inputDisabled.value;
  };

  const clearData = () => {
    model.value = {};
    selectedRowKeys.value = [];
  };

  const editGroup = () => {
    if (!selectedRowKeys.value?.length) {
      NsMessage.warn('请先选择需要编辑的分组');
      return;
    }
    inputDisabled.value = false;
  };
  //点击对钩按钮处理保存逻辑
  const add = () => {
    const finalParams = { ...props.params, ...model.value };
    if (opType) {
      delete finalParams.id;
    }
    editGroupRef.value.triggerSubmit().then(() => {
      http.post(group.saveComputeGroup, finalParams).then(() => {
        getTableData();
        NsMessage.success('操作成功');
        op();
      });
    });
  };

  const delGroup = (id) => {
    http.post(group.delComputeGroup, { id }).then(() => {
      getTableData();
      NsMessage.success('操作成功');
      clearData();
    });
  };
  const rowSelectChange = (selected, selectedRows) => {
    opType = false;
    console.log(selectedRowKeys, selectedRows);
    selectedRowKeys.value = selected;
    model.value = { ...selectedRows[0] };
  };
  const mockDataSource = ref([]);
  const getTableData = () => {
    http.post(group.queryComputeGroup, props.params).then((res) => {
      mockDataSource.value = res.data;
    });
  };
  const getCode = () => {
    http.post(group.computeGroupNum, props.params).then((res) => {
      model.value.groupNum = res.data;
    });
  };
  const basicTableConfig = ref({
    bordered: true,
    placeholder: '请输入',

    pagination: false,
    rowKey: (record) => record.id,
    columns: [
      {
        title: '分组编号',
        dataIndex: 'groupNum',
        // customRender: ({ index }) => index + 1,
        width: 80,
        align: 'center',
      },
      {
        title: '分组名称',
        dataIndex: 'groupName',
        align: 'center',
      },
      {
        title: '删除',
        dataIndex: 'delete',
        width: 80,
        align: 'center',
        customRender: ({ record }) =>
          createVNode(
            Popconfirm,
            { title: '确定删除吗?', placement: 'leftTop', onConfirm: () => delGroup(record.id) },
            () => [
              createVNode(DeleteOutlined, {
                style: { color: 'red', cursor: 'pointer' },
                title: '删除',
                // onClick: () => delGroup(record.id),
              }),
            ],
          ),
      },
    ],
  });

  const schemas = (val) => {
    return [
      {
        field: 'basicInfo',
        label: '',
        displayFormItem: false,
        class: 'ns-form-item-full',
        component: 'NsChildForm',
        componentProps: {
          title: '分组信息',
          schemas: [
            {
              label: '分组id',
              field: 'id',
              component: 'NsInput',
              show: false,
            },
            {
              label: '分组编号',
              field: 'groupNum',
              component: 'NsInput',
              componentProps: {
                disabled: true,
                placeholder: '请输入',
              },
            },
            {
              label: '分组名称',
              field: 'groupName',
              component: 'NsInput',
              componentProps: {
                placeholder: '请输入',
                disabled: val,
              },
              rules: [{ required: true }],
            },
          ],
        },
      },
      // {
      //   field: 'list',
      //   label: '',
      //   displayFormItem: false,
      //   class: 'ns-form-item-full',
      //   component: 'NsChildForm',
      //   componentProps: {
      //     title: '分组列表',
      //     schemas: [
      //       {
      //         label: '',
      //         field: 'NsBasicTable',
      //         component: 'NsBasicTable',
      //         formItemProps: {
      //           wrapperCol: { span: 24 },
      //         },
      //         componentProps: {
      //           bordered: true,
      //           disabled: true,
      //           placeholder: '请输入',
      //           dataSource: mockDataSource.value,
      //           rowSelection: { type: 'radio', onChange: rowSelectChange },
      //           pagination: false,
      //           rowKey: (record) => record.groupName,
      //           columns: [
      //             {
      //               title: '序号',
      //               dataIndex: 'name',
      //               customRender: ({ index }) => index + 1,
      //               width: 80,
      //               align: 'center',
      //             },
      //             {
      //               title: '分组名称',
      //               dataIndex: 'groupName',
      //               align: 'center',
      //             },
      //             {
      //               title: '删除',
      //               dataIndex: 'delete',
      //               width: 80,
      //               align: 'center',
      //               customRender: ({ index }) =>
      //                 createVNode(DeleteOutlined, {
      //                   style: { color: 'red', cursor: 'pointer' },
      //                   onClick: () => deleteRow(index),
      //                 }),
      //             },
      //           ],
      //         },
      //       },
      //     ],
      //   },
      // },
    ];
  };

  const btnClick = () => {
    if (!selectedRowKeys.value[0]) {
      NsMessage.warn('请选择分组');
      return;
    }
    http
      .post(group.saveComputeGroupInfo, {
        ...props.params,
        groupListId: selectedRowKeys.value[0],
      })
      .then(() => {
        emit('sure');
        toggle();
        NsMessage.success('操作成功');
      });
  };

  defineExpose({
    toggle,
  });
</script>
<style scoped lang="less">
  .drawerContainer {
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
  .iconOP {
    cursor: pointer;
    color: @primary-color;
  }
</style>
