import { useEffect, useState } from 'react';
import { Button, Image, message, Modal, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import SearchView from '~/components/search-box';
import { CategoryManageAPI, MallManageAPI } from '~/api';
import { InterListType, InterReqListType } from '~/api/interface';
import { listCompanyInspectionPageType } from '~/api/interface/mallManageType';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';

// 列表类型
type TableType = InterListType<listCompanyInspectionPageType>;
// 请求的参数
type ReqType = InterReqListType<listCompanyInspectionPageType>;
// 搜索表单的数据
let query: ReqType = {};

const ServiceListView = () => {
  // 路由钩子
  const navigate = useNavigate();
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  // 行业应用列表
  const [industryList, setIndustryList] = useState<
    { label: string; value: number; children: { label: string; value: number }[] }[]
  >([]);
  // 获取行业列表
  const getIndustryList = async () => {
    const res = await CategoryManageAPI.industryListPages({
      pageNo: 1,
      pageSize: 9999,
    });
    if (res && res.code === '200') {
      const list = res.result?.list || [];
      setIndustryList(
        list.map((i) => ({
          label: i.typeName,
          value: i.id,
          children: i.inspectionDTOS?.map((j) => {
            return {
              label: j.inspectionName,
              value: j.id,
            };
          }),
        })),
      );
    }
  };
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await MallManageAPI.listCompanyInspectionPage({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list || []);
      // console.log(list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType & { cascaderData: number[] }) => {
    const obj = {
      ...data,
      industryTypeId: data.cascaderData?.length >= 1 ? data.cascaderData[0] : undefined,
      inspectionId: data.cascaderData?.length === 2 ? data.cascaderData[1] : undefined,
    };
    pagination.current = 1;
    query = obj;
    getTableList(obj).then();
  };
  // 新增服务
  const handleAdd = () => {
    navigate('/serviceManage/serviceDetail');
  };
  // 跳转详情
  const handleDetail = (record: TableType[0]) => {
    navigate(`/serviceManage/serviceDetail?id=${record.id}`);
  };
  // 删除服务
  const handleDelete = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '是否删除该服务？',
      onOk: async () => {
        const res = await MallManageAPI.companyInspectionRemove({ id: record.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(pagination.current, pagination.pageSize);
        }
      },
    });
  };
  // 上下架
  const handleState = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: `是否${record.saleState === 1 ? '下架' : '上架'}该服务？`,
      onOk: async () => {
        const res = await MallManageAPI.companyInspectionUpdate({
          id: record.id,
          saleState: record.saleState === 1 ? 0 : 1,
        });
        if (res && res.code === '200') {
          message.success(`${record.saleState === 1 ? '下架' : '上架'}成功`);
          paginationChange(pagination.current, pagination.pageSize);
        }
      },
    });
  };
  // 价格单位列表
  const [priceUnitList, setPriceUnitList] = useState<{ id: number; unitName: string }[]>([]);
  // 获取价格单位
  const getPriceUnit = async () => {
    const res = await MallManageAPI.listInspectionPriceUnit({});
    if (res && res.code === '200') {
      setPriceUnitList(res.result || []);
    }
  };
  // 获取商品的价格单位
  const getPriceUnitStr = (i: TableType[0]) =>
    priceUnitList.find((j) => j.id === i?.inspectionPriceUnitId)?.unitName || '';
  // 飞手团队列表
  const [companyInfoList, setCompanyInfoList] = useState<{ label: string; value: number }[]>([]);
  // 获取飞手团队列表
  const getListCompanyInfoByCoopId = async () => {
    const res = await MallManageAPI.listCompanyInfoByCoopId({
      lat: 22,
      lon: 113,
      pageNo: 1,
      pageSize: 9999,
      coopId: 5,
    });
    if (res && res.code === '200') {
      const list = res.result?.list?.map((i) => ({ label: i.companyName, value: i.id }));
      setCompanyInfoList(list || []);
    }
  };
  // 组件挂载
  useEffect(() => {
    getIndustryList().then();
    getPriceUnit().then();
    getListCompanyInfoByCoopId().then();
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      width: '50px',
      render: (_text, _record, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '服务编号',
      dataIndex: 'id',
      align: 'center',
      render: (_text, record) => record.inspectionDTO.inspectionNo,
    },
    {
      title: '服务名称',
      dataIndex: 'id',
      align: 'center',
      render: (_text, record) => record.inspectionDTO.inspectionName,
    },
    {
      title: '行业应用',
      dataIndex: 'id',
      align: 'center',
      render: (_text, record) => record.industryTypeDTO.typeName,
    },
    {
      title: '作业团队',
      dataIndex: 'companyName',
      align: 'center',
      width: '150px',
      ellipsis: true,
    },
    {
      title: '服务主图',
      dataIndex: 'inspectionFirstImg',
      align: 'center',
      render: (text) => (
        <>
          <Image src={text} width={40} height={40} />
        </>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      align: 'center',
      render: (text, record) => (
        <>
          ￥{text.toLocaleString()}/{getPriceUnitStr(record)}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'saleState',
      align: 'center',
      render: (text) => (text === 1 ? '上架' : '下架'),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      width: '100px',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      width: '150px',
      fixed: 'right',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              handleDetail(record);
            }}
          >
            详情
          </Button>
          <Button
            type={'link'}
            danger
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Button>
          <Button
            type={'link'}
            onClick={() => {
              handleState(record);
            }}
          >
            {record.saleState === 1 ? '下架' : '上架'}
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchView
        child={
          <>
            <Button
              type='primary'
              onClick={() => handleAdd()}
              icon={<PlusOutlined />}
              disabled={!!userInfo.roleInfo.superAdmin}
            >
              新增服务
            </Button>
          </>
        }
        search={[
          {
            label: '服务名称',
            placeholder: '请输入服务编号、名称',
            type: 'input',
            name: 'keyword',
          },
          {
            label: '行业应用',
            placeholder: '请选择行业应用',
            type: 'Cascader',
            name: 'cascaderData',
            options: industryList,
          },
          {
            label: '作业团队',
            placeholder: '请选择作业团队',
            type: 'Select',
            name: 'companyInfoId',
            options: companyInfoList,
          },
        ]}
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1000 }}
        bordered
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
    </>
  );
};

export default ServiceListView;
