import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Descriptions, Image, message, Modal, Table } from 'antd';
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons';
import SearchBox from '~/components/search-box';
import qs from 'query-string';
import { inspectionDetailType, listByInspectionIdType } from '~/api/interface/categoryManage';
import { InterDataType, InterItemType } from '~/api/interface';
import { CategoryManageAPI } from '~/api';
import { ColumnsType } from 'antd/es/table';
import AddEditTagModalView from '~/pages/categoryManage/serviceCategoryList/comp/addEditTagModal';
import Video from '~/components/video';

// 表格类型
type TableType = InterItemType<listByInspectionIdType>;

const ServiceCategoryDetail: React.FC = () => {
  // 路由钩子
  const location = useLocation();
  // 导航钩子
  const navigate = useNavigate();
  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };
  // 新增编辑标签是否显示
  const [addEditVisible, setAddEditVisible] = useState(false);
  // 编辑的数据
  const [recordData, setRecordData] = useState<TableType[0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 加载列表
  const getTableList = async () => {
    // 只需要修改这个地方的接口即可
    const res = await CategoryManageAPI.listByInspectionId({
      id: Number(qs.parse(location.search).id),
    });
    if (res && res.code === '200') {
      const { result } = res; // 解构
      setTableData(result || []);
    }
  };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '是否删除该场景标签？',
      onOk: async () => {
        const res = await CategoryManageAPI.inspectionTagDelete({
          id: record.id,
        });
        if (res && res.code === '200') {
          message.success('删除成功');
          await getTableList();
        }
      },
    });
  };
  // 服务详情
  const [inspectionDetail, setInspectionDetail] = useState<InterDataType<inspectionDetailType>>();
  // 获取服务详情
  const getInspectionDetail = async () => {
    const res = await CategoryManageAPI.inspectionDetail({
      id: Number(qs.parse(location.search).id),
    });
    if (res && res.code === '200') {
      setInspectionDetail(res.result);
    }
  };
  // 获取图片
  const getImgParse = (text: string) => {
    try {
      return JSON.parse(text);
    } catch (e) {
      return [{ fileUrl: text }];
    }
  };
  // 组件挂载
  useEffect(() => {
    getInspectionDetail().then();
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'tagName',
      align: 'center',
      render: (_text, _record, index) => `${index + 1}`,
    },
    {
      title: '场景标签',
      dataIndex: 'tagName',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      width: 200,
      render: (_text, record) => (
        <>
          <Button
            type='link'
            size='small'
            onClick={() => {
              setRecordData(record);
              setAddEditVisible(true);
            }}
          >
            编辑
          </Button>
          <Button type='link' size='small' onClick={() => handleDelete(record)} danger>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        child={
          <Button type={'primary'} icon={<ArrowLeftOutlined />} onClick={() => handleBack()}>
            返回
          </Button>
        }
      />
      <Descriptions
        title='子分类详情'
        bordered
        style={{ marginBottom: '20px', width: '60%' }}
        column={2}
        labelStyle={{ width: '15%' }}
        contentStyle={{ width: '30%' }}
      >
        <Descriptions.Item label='分类名称'>{inspectionDetail?.inspectionName}</Descriptions.Item>
        <Descriptions.Item label='分类图标'>
          <Image src={inspectionDetail?.inspectionImg} width={40} height={40} />
        </Descriptions.Item>
        <Descriptions.Item label='分类描述'>
          {inspectionDetail?.inspectionDescription}
        </Descriptions.Item>
        <Descriptions.Item label='服务编号'>{inspectionDetail?.inspectionNo}</Descriptions.Item>
        <Descriptions.Item label='业务案例图片'>
          {getImgParse(inspectionDetail?.caseImg as string).map(
            (i: { fileUrl: string }, j: React.Key) => (
              <Image src={i.fileUrl} width={40} height={40} key={j} />
            ),
          )}
        </Descriptions.Item>
        <Descriptions.Item label='业务案例视频'>
          {inspectionDetail?.caseVideo && (
            <Video src={inspectionDetail?.caseVideo} width={40} height={40} />
          )}
        </Descriptions.Item>
      </Descriptions>
      <SearchBox
        sufFixBtn={
          <Button
            type={'primary'}
            icon={<PlusOutlined />}
            onClick={() => {
              setRecordData(undefined);
              setAddEditVisible(true);
            }}
          >
            新增场景标签
          </Button>
        }
      />
      <Table
        style={{ width: '60%' }}
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        // scroll={{ x: 1500 }}
        bordered
        pagination={{
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <AddEditTagModalView
        title={recordData ? '编辑场景标签' : '新增场景标签'}
        open={addEditVisible}
        data={recordData}
        id={Number(qs.parse(location.search).id)}
        onCancel={() => {
          setAddEditVisible(false);
          setRecordData(undefined);
          getTableList().then();
        }}
      />
    </>
  );
};

export default ServiceCategoryDetail;
