import React, { useState, useRef, forwardRef, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Modal, Form, Select, Table, Card, Row, Col, Input, Button, message } from 'antd';
import { set } from 'lodash';
import { da } from 'date-fns/locale';
import { columns, repastTypeList } from './data';
import EditRepastModal from './editRepastModal';
import AddModal from './addModal';
import styles from './index.less';
import { stringOrObjectTrim } from '@/utils/utils';
import {
  setShopList,
  setShopDelete,
  mealTypeList,
  apiEnterpriseList,
  businessTypeCheck,
} from './service.js';

const { confirm } = Modal;
const StoreManagement = () => {
  const [page, setPage] = useState({
    current: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [searchForm, setSearchForm] = useState({});
  const formRef = useRef(null);
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [repastType, setRepastType] = useState([]);
  const [repastId, setRepastId] = useState(null);
  const [enterpriseList, setEnterpriseList] = useState();
  const [firstEnterprise, setFirstEnterprise] = useState('');
  const [enterprise, setEnterprise] = useState({});
  const [dataList, setDataList] = useState([]);
  const [name, setName] = useState('');
  const [isStore, setIsStore] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selectMealType, setSelectMealType] = useState([]);
  const shopList = async params => {
    // 去掉前后空格
    const data = stringOrObjectTrim(params);
    setLoading(true);
    const res = await setShopList(data);
    if (res?.businessCode === '0000') {
      setLoading(false);
      setDataList(res.data?.records);
      setTotal(res.data?.total);
      return;
    }
    setTimeout(() => {
      setLoading(false);
      setDataList([]);
      setTotal(0);
    }, 5000);
  };

  // 企业查询
  const getEnterpriseList = async () => {
    const res = await apiEnterpriseList();
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      const firstOption = list[0].id;
      const optionData = list.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setEnterprise({ value: list[0].id, label: list[0].name });
      setFirstEnterprise(firstOption);
      setEnterpriseList(optionData);
      setSearchForm({ enterpriseId: firstOption });
      shopList({ data: { enterpriseId: firstOption }, ...page });
    }
  };
  useEffect(() => {
    getEnterpriseList();
  }, []);

  // 关闭弹框
  const closeModal = (status, val) => {
    if (status) {
      const pageInfo = {
        current: 1,
        pageSize: 10,
      };
      setPage(pageInfo);
      shopList({ data: searchForm, ...pageInfo });
    }
    if (val === 'edit') {
      setIsStore(false);
      setEditVisible(false);
      setRepastType([]);
      setSelectMealType([]);
      return;
    }
    setName(false);
    setAddVisible(false);
  };
  const getMealTypeList = async id => {
    const res = await mealTypeList({ id });
    if (res.businessCode === '0000') {
      const resData = res.data;
      const data = [];
      repastTypeList.forEach(item => {
        if (resData.includes(item.value) && item.value !== 4) {
          data.push(item);
        }
      });
      if (resData.includes(4)) {
        setIsStore(true);
      }
      setRepastType(data);
      setEditVisible(true);
    }
  };
  // 修改餐饮类型
  const editRepastType = ({ id, mealType }) => {
    setSelectMealType(mealType);
    setRepastId(id);
    getMealTypeList(id);
  };
  // 删除
  const editShop = async id => {
    const res = await setShopDelete({ id });
    if (res.businessCode === '0000') {
      message.success('删除成功！');
      shopList({ ...page, data: searchForm });
    }
  };
  // 删除
  const delShop = ({ shopName, id }) => {
    confirm({
      title: `确认删除企业商户#${shopName || ''}#?`,
      content: '注：删除微店后，其商户下企业商品一并删除',
      onOk() {
        editShop(id);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const onChange = (value, option) => {
    setFirstEnterprise(value);
    const values = formRef.current.getFieldsValue();
    const pageInfo = {
      current: 1,
      pageSize: 10,
    };
    setPage(pageInfo);
    setSearchForm(values);
    shopList({ ...pageInfo, data: values });
    setEnterprise(option);
  };
  // 添加商户
  const addShop = async () => {
    const res = await businessTypeCheck({ enterpriseId: searchForm.enterpriseId });
    if (res.businessCode === '0000') {
      setName(enterprise.label);
      setAddVisible(true);
    }
  };
  // 搜索
  const onFinish = async values => {
    setSearchForm(values);
    const pageInfo = {
      current: 1,
      pageSize: 10,
    };
    setPage(pageInfo);
    shopList({ data: values, ...pageInfo });
  };
  // 重置
  const onReset = () => {
    formRef.current.resetFields();
    const pageInfo = {
      current: 1,
      pageSize: 10,
    };
    setPage(pageInfo);
    setSearchForm({ enterpriseId: firstEnterprise });
    shopList({ data: { enterpriseId: firstEnterprise }, ...pageInfo });
  };
  // 分页
  const handleTableChange = (current, pageSize) => {
    const pageInfo = {
      current,
      pageSize,
    };
    setPage(pageInfo);
    shopList({ data: searchForm, ...pageInfo });
  };

  const pagination = {
    ...page,
    total,
    showTotal: t => `共 ${t} 条`,
    onChange: handleTableChange,
    onShowSizeChange: handleTableChange,
  };

  const res = {
    editRepastType,
    delShop,
  };
  return (
    <PageHeaderWrapper>
      <Card className={styles.card}>
        {firstEnterprise && (
          <Form ref={formRef} onFinish={onFinish}>
            <Row gutter={24}>
              <Col span={8}>
                <Form.Item
                  label="企业名称"
                  name="enterpriseId"
                  wrapperCol={{ span: 16 }}
                  rules={[{ required: true }]}
                  initialValue={firstEnterprise}
                >
                  <Select
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    onChange={onChange}
                    options={enterpriseList}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="微店名称" name="shopName" wrapperCol={{ span: 16 }}>
                  <Input maxLength="20" allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="微店ID" name="shopId" wrapperCol={{ span: 16 }}>
                  <Input maxLength="20" allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="餐品类型" name="mealType" wrapperCol={{ span: 16 }}>
                  <Select
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    options={repastTypeList}
                    placeholder="全部"
                  />
                </Form.Item>
              </Col>
              <Col className={styles.btn}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button htmlType="button" onClick={onReset} className={styles.left}>
                    重置
                  </Button>
                  <Button type="primary" onClick={addShop} className={styles.left}>
                    添加商户
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        )}
      </Card>
      <Card>
        <Table
          columns={columns(res)}
          dataSource={dataList}
          rowKey={r => r.id}
          bordered
          pagination={pagination}
          loading={loading}
        />
      </Card>
      <EditRepastModal
        editVisible={editVisible}
        repastType={repastType}
        id={repastId}
        onCancel={closeModal}
        enterpriseId={searchForm.enterpriseId}
        isStore={isStore}
        selectMealType={selectMealType}
      />

      <AddModal
        addVisible={addVisible}
        enterpriseId={searchForm.enterpriseId}
        name={name}
        onCancel={closeModal}
      />
    </PageHeaderWrapper>
  );
};
export default StoreManagement;
