<template>
  <div>
    <BasicTable @register="registerTable" v-show="isStatus === 0">
      <template #toolbar>
        <Authority value="api:yt:convert:js:post">
          <a-button type="primary" @click="handleCreate"> 新增转换脚本 </a-button>
        </Authority>
        <Authority value="api:yt:convert:js:delete">
          <Popconfirm
            title="您确定要批量删除数据"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDeleteOrBatchDelete(null)"
          >
            <a-button color="error" :disabled="hasBatchDelete"> 批量删除 </a-button>
          </Popconfirm>
        </Authority>
      </template>
      <template #status="{ record }">
        <Switch
          :checked="record.status === 1"
          :loading="record.pendingStatus"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          @change="(checked:boolean)=>statusChange(checked,record)"
        />
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '查看',
              auth: 'api:yt:convert:js:get',
              icon: 'ant-design:eye-outlined',
              onClick: handleView.bind(null, record),
              ifShow: record.status == 1,
            },
            {
              label: '编辑',
              auth: 'api:yt:convert:js:update',
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              ifShow: record.status == 0,
            },
            {
              label: '删除',
              auth: 'api:yt:convert:js:delete',
              icon: 'ant-design:delete-outlined',
              ifShow: record.status == 0,
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDeleteOrBatchDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <ScriptDrawer
      @register="registerDrawer"
      @isStatus="handleIsStatus"
      ref="scriptDrawerRef"
      @success="handleSuccess"
    />
    <TestScript v-show="isStatus === 1" @isStatus="handleCancelStatus" ref="testScriptRef" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { Switch, Popconfirm } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { columns, searchFormSchema } from './config/config.data';
  import { getConvertApi, deleteTransformApi } from '/@/api/device/TransformScriptApi';
  import { useDrawer } from '/@/components/Drawer/index';
  import ScriptDrawer from './cpns/ScriptDrawer.vue';
  import TestScript from './cpns/TestScript.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { updateTransformScriptStatusApi } from '/@/api/device/TransformScriptApi';
  import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
  import { Authority } from '/@/components/Authority';

  const handleSuccess = () => {
    reload();
  };

  const [registerTable, { reload, setProps, setSelectedRowKeys }] = useTable({
    api: getConvertApi,
    title: '转换脚本列表',
    columns,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
    },
    clickToRowSelect: 'false',
    rowKey: 'id',
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
  });

  const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
    useBatchDelete(deleteTransformApi, handleSuccess, setProps);
  selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
    // Demo:status为1的选择框禁用
    if (record.status === 1) {
      return { disabled: true };
    } else {
      return { disabled: false };
    }
  };
  nextTick(() => {
    setProps(selectionOptions);
  });
  const [registerDrawer, { openDrawer }] = useDrawer();

  const isStatus = ref(0);
  const testScriptRef = ref();
  const scriptDrawerRef = ref();
  const handleIsStatus = ({ status, jsCode }) => {
    isStatus.value = status;
    testScriptRef.value.aceEditor.setValue(jsCode);
  };
  const handleCancelStatus = ({ status, emitType }) => {
    openDrawer(true);
    isStatus.value = status;
    if (emitType === 'ok') {
      const jsCode = testScriptRef.value.aceEditor.getValue();
      scriptDrawerRef.value.aceEditor.setValue(jsCode);
    }
  };
  const handleCreate = () => {
    nextTick(() => {
      openDrawer(true, {
        isUpdate: false,
      });
    });
  };
  const handleEdit = (record: Recordable) => {
    nextTick(() => {
      openDrawer(true, { isUpdate: true, record });
    });
  };
  const statusChange = async (checked, record) => {
    setProps({
      loading: true,
    });
    setSelectedRowKeys([]);
    resetSelectedRowKeys();
    const newStatus = checked ? 1 : 0;
    const { createMessage } = useMessage();
    try {
      await updateTransformScriptStatusApi(newStatus, record.id);
      if (newStatus) {
        createMessage.success(`启用成功`);
      } else {
        createMessage.success('禁用成功');
      }
    } finally {
      setProps({
        loading: false,
      });
      reload();
    }
  };
  function handleView(record: Recordable) {
    nextTick(() => {
      openDrawer(true, {
        record,
        isUpdate: 'view',
      });
    });
  }
</script>
