import React, { useEffect, useState } from 'react';
import './index.scss';
import { Button, Form, Input, message, Modal, Select, Table } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
import { ProduceManageAPI } from '~/api';
import AddOrEditProduce from './components/addOrEditProduceModal';
import { ProductSkuType, MakeItemEntity } from './propsType';
import useOption from '~/common/hook/optionHook';
// import { categoryDec } from '@/api/modules/goods';

const { Option } = Select;
const { confirm } = Modal;
// 搜索表单的数据
let query: any = {};

// 表单提交
interface FormType {
  productName?: string;
  goodsTypeId?: number;
}

function ProduceManage() {
  // 路由操作
  const navigate = useNavigate();
  // 表格数据
  const [tableData, setTableData] = useState<any>([{ id: 1 }]);
  // 加载中
  const [loading, setLoading] = useState<boolean>(false);
  // 产品类型下拉列表
  const [productTypeSelectList, setProductTypeSelectList] = useState<
    { label: string; val: number }[]
  >([]);
  // 新增弹窗是否显示
  const [visibleAddEdit, setVisibleAddEdit] = useState(false);
  // 新增弹窗内容
  const [addEditData, setAddEditData] = useState<ProductSkuType>();
  // 品牌列表
  const [makeList, setMakeList] = useState<MakeItemEntity[]>([]);
  // 目录列表
  const [decList, setDecList] = useState<any>([]);
  // 跳转详情
  const handleDetail = (record: ProductSkuType) => {
    navigate({
      pathname: '/mallManage/produceDetail',
      search: `id=${record.id}`,
    });
  };
  // 新增弹窗
  const handleAdd = () => {
    setVisibleAddEdit(true);
    setAddEditData(undefined);
  };
  // 编辑弹窗
  const handleEdit = (record: ProductSkuType) => {
    setVisibleAddEdit(true);
    setAddEditData(record);
  };
  // 关闭弹窗
  const handleAddEditClosed = () => {
    setVisibleAddEdit(false);
    setAddEditData(undefined);
    paginationChange(pagination.current, pagination.pageSize);
  };
  // 删除产品
  const handleDelete = (record: ProductSkuType) => {
    confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      async onOk() {
        const res: any = await ProduceManageAPI.removeProductSku({ id: record.id });
        if (res && res.code === '200') {
          await message.success('操作成功');
          await paginationChange(pagination.current, pagination.pageSize);
        } else {
          message.error(res.message);
        }
      },
    });
  };
  // 表格结构
  const columns: ColumnsType<ProductSkuType> = [
    {
      title: '产品名称',
      dataIndex: 'productName',
      align: 'center',
      fixed: 'left',
    },
    {
      title: '产品目录',
      dataIndex: 'directoryId',
      align: 'center',
      render: (text: string, record: ProductSkuType) =>
        decList.find((v) => v.id === record.directoryId)?.sortName || '',
    },
    { title: '产品类型', dataIndex: 'typeName', align: 'center' },
    { title: '型号', dataIndex: 'model', align: 'center' },
    { title: '产品品牌', dataIndex: 'productBrand', align: 'center' },
    {
      title: '操作',
      align: 'center',
      width: '15%',
      fixed: 'right',
      render: (text: string, record) => {
        return (
          <div>
            <Button type='link' onClick={() => handleDetail(record)}>
              详情
            </Button>
            <Button type='link' onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type='link' onClick={() => handleDelete(record)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 按钮权限
  const btnAdd = useOption(22151);
  const btnEdit = useOption(22152);
  const btnDelete = useOption(22153);
  const btnDetail = useOption(22154);

  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    setLoading(true);
    // 只需要修改这个地方的接口即可
    const res: any = await ProduceManageAPI.listPageProductSku({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    setLoading(false);
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        pageSize,
        current: pageNo,
        totalPage,
      });
      setTableData(list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (val: FormType) => {
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
      }).filter((i) => i[1] !== '' && i[1] !== undefined && i[1] !== null),
    );
    query = data;
    getTableList(data).then();
  };

  // 获取产品类型列表
  const getListGoodsTypeList = async (type: number) => {
    const res: any = await ProduceManageAPI.getListGoodsTypeList(type);
    if (res && res.code === '200') {
      const arr = res.result.map((i: { goodsMasterType: string; goodsMasterTypeId: number }) => {
        return {
          label: i.goodsMasterType,
          val: i.goodsMasterTypeId,
        };
      });
      setProductTypeSelectList(arr);
    }
  };
  // 获取品牌列表
  const getMakeList = () => {
    ProduceManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 999999 }).then(({ code, result }) => {
      setMakeList(result.list || []);
    });
  };
  // 目录列表
  const getDescList = () => {
    ProduceManageAPI.directoryList().then((res: any) => {
      if (res.result) {
        setDecList(res.result.filter((v: any) => v.id !== 2));
      }
    });
  };
  // 目录修改
  const decSelectChange = (value: number) => {
    if (value) {
      getListGoodsTypeList(value);
    }
  };
  // componentDidMount
  useEffect(() => {
    // query = {};
    // getMakeList();
    // getDescList();
    // (async () => {
    //   await getTableList();
    // })();
  }, []);

  return (
    <div className='from-table-wrap'>
      <div className='header-view'>
        <Form name='basic' layout='inline' onFinish={onFinish}>
          {btnAdd || true ? (
            <Form.Item>
              <Button type='primary' onClick={handleAdd}>
                新增
              </Button>
            </Form.Item>
          ) : (
            ''
          )}

          <Form.Item name='productName' label='产品名称'>
            <Input placeholder='请输入产品名称' allowClear />
          </Form.Item>
          <Form.Item name='directoryId' label='产品目录'>
            <Select placeholder='请选择产品目录' onChange={decSelectChange} allowClear>
              {decList.map((v, index: number) => (
                <Select.Option value={v.id} key={index}>
                  {v.sortName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name='goodsTypeId' label='产品类型'>
            <Select placeholder='请选择产品类型' allowClear>
              {productTypeSelectList.map((i, j) => (
                <Option value={i.val} key={j}>
                  {i.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table
        size='small'
        dataSource={tableData}
        loading={loading}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1500 }}
        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} 条数据`,
        }}
      />
      <AddOrEditProduce
        visible={visibleAddEdit}
        closed={handleAddEditClosed}
        data={addEditData}
        makeList={makeList}
        decList={decList}
      />
    </div>
  );
}
export default ProduceManage;
