import { getAPIBaseUrl, handleDownLoadFile } from '@/api/utils';
import useLoading from '@/hooks/loading';
import { getToken, getTokenFrom } from '@/utils/auth';
import {
  Button,
  Col,
  type FileItem,
  Message,
  Modal,
  Notification,
  Row,
  Space,
  Table,
  type TableColumnData,
  type TableData,
  Tag,
  Upload
} from '@arco-design/web-vue';
import { isArray } from 'lodash';
import { defineComponent, reactive, ref } from 'vue';
import type { KamiApiCardInfoCTripV1AccountCookieCheckRes } from '@/api/generated';
import { apiClient } from '@/api';

const tableColumns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    render: (data: { rowIndex: number }) => {
      return data.rowIndex + 1;
    }
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '昵称',
    dataIndex: 'nickname'
  },
  {
    title: '限额(金额)',
    dataIndex: 'maxAmountLimit'
  },
  {
    title: '限额(次数)',
    dataIndex: 'maxCountLimit'
  },
  {
    title: 'cookie',
    dataIndex: 'cookie',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '是否存在系统内',
    dataIndex: 'isExist',
    render: (data: { record: TableData }) => {
      let color = 'red';
      let text = '不存在';
      if (data.record.isExist) {
        color = 'green';
        text = '存在';
      }
      return (
        <Tag size='small' color={color}>
          {text}
        </Tag>
      );
    }
  },
  {
    title: '是否可用',
    dataIndex: 'isAvailable',
    render: (data: { record: TableData }) => {
      let color = 'red';
      let text = '不可用';
      if (data.record.isAvailable) {
        color = 'green';
        text = '可用';
      }
      return (
        <Tag size='small' color={color}>
          {text}
        </Tag>
      );
    }
  }
];

export const notification = (
  isSucceed: boolean = true,
  nickname: string = '',
  balance: number = 0,
  isExist: boolean = false
) => {
  if (isSucceed) {
    const id = `${Date.now()}`;
    Notification.success({
      id,
      title: '用户信息',
      content: () => (
        <div>
          <div>用户昵称：{nickname}</div>
          <div>用户余额：{balance}</div>
          <div>是否存在于系统：{isExist ? '存在' : '不存在'}</div>
        </div>
      ),
      closable: true,
      footer: () => (
        <Space>
          <Button
            status='normal'
            type='primary'
            onClick={() => Notification.remove(id)}
          >
            确认
          </Button>
        </Space>
      ),
      duration: 0
    });
  } else {
    const id = `${Date.now()}`;
    Notification.error({
      id,
      title: '用户信息',
      content: 'cookie无效',
      footer: () => (
        <Space>
          <Button
            status='danger'
            type='primary'
            onClick={() => Notification.remove(id)}
          >
            确认
          </Button>
        </Space>
      ),
      duration: 0
    });
  }
};

// 新增下载模板文件的函数
const downloadDataList = async () => {
  const response = await apiClient.apiCardInfoCTripAccountDownloadGet({
    responseType: 'blob'
  });
  handleDownLoadFile(response.data as any, '携程下载数据.xlsx');
};

export const batchImportModel = defineComponent({
  name: 'batchImportCtripAccountModel',
  emits: {
    close: () => {}
  },
  setup(props, { emit }) {
    const state = reactive<{
      visible: boolean;
    }>({
      visible: false
    });
    const { loading, setLoading } = useLoading(false);
    const tableData = ref<KamiApiCardInfoCTripV1AccountCookieCheckRes[]>([]);

    return () => (
      <>
        <Button
          type='primary'
          size='small'
          onClick={() => (state.visible = !state.visible)}
        >
          导入
        </Button>
        <Modal
          title='批量导入'
          width='80%'
          v-model:visible={state.visible}
          onBeforeOk={async (done: (closed: boolean) => void) => {
            try {
              await apiClient.apiCardInfoCTripAccountBatchAddPost({
                kamiApiCardInfoCTripV1AccountCookieBatchAddReq: {
                  list: tableData.value
                }
              });
              emit('close');
              Message.success('上传成功');
              done(true);
            } catch {
              Message.error('上传失败');
              done(false);
            }
          }}
        >
          <Row gutter={20}>
            <Col span={4}>
              <Space direction='vertical' fill>
                <Button
                  long
                  status='warning'
                  onClick={() => downloadDataList()}
                >
                  下载模板
                </Button>
                <Upload
                  disabled={loading.value}
                  onBeforeUpload={async (
                    file: File
                  ): Promise<boolean | File> => {
                    setLoading(true);
                    tableData.value = [];
                    return file;
                  }}
                  draggable
                  limit={1}
                  accept='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                  onSuccess={(fileItem: FileItem) => {
                    setLoading(false);
                    if (fileItem.response.code === 0) {
                      if (
                        isArray(fileItem.response.data.list) &&
                        fileItem.response.data.list.length > 0
                      ) {
                        tableData.value = fileItem.response.data.list;
                      }
                      Message.success(
                        `上传成功${fileItem.response.data?.msg ? '：' + fileItem.response.data?.msg : ''}`
                      );
                      return;
                    }
                    Message.error(`上传失败：${fileItem.response.message}`);
                  }}
                  onError={() => {
                    Message.error('上传失败');
                    setLoading(false);
                  }}
                  action={`${getAPIBaseUrl()}/api/cardInfo/cTrip/account/check`}
                  headers={{
                    Authorization: `Bearer ${getToken()}`,
                    tokenFrom: getTokenFrom()
                  }}
                  tip='点击批量上传ck'
                />
              </Space>
            </Col>
            <Col span={20}>
              <Table
                pagination={false}
                loading={loading.value}
                data={tableData.value}
                columns={tableColumns}
              ></Table>
            </Col>
          </Row>
        </Modal>
      </>
    );
  }
});
