import React, { useState, useRef, useEffect } from 'react';
import {
  notification,
  Button,
  Form,
  Input,
  Cascader,
  Col,
  Row,
  Table,
  Pagination,
  Modal,
  Select,
} from 'antd';
import _ from 'lodash';
import { el } from 'date-fns/locale';
import { searchList, apiEnableStore, apiAddrArea, apiproductBusiness } from './services';
import { stateDesc, weeks, layout, businessStatus, businessList } from './data';
import StoreModal from './components/storeModal';
import style from './style.less';

const { Option } = Select;
const { confirm } = Modal;
export default () => {
  const [visible, setVisible] = useState(false);
  const [storeInfo, setStoreInfo] = useState({});
  const [areaAddr, setAreaAddr] = useState([]);
  const [status, setStatus] = useState();
  const [dataList, setDataList] = useState([]);
  const [pageNo, setPageNo] = useState(1);
  const [totalNum, setTotalNum] = useState(0);
  const [pageSize, setPageSize] = useState(20);
  const [productBusiness, setProductBusiness] = useState([]);
  const refSearch = useRef();
  const divDom = useRef();
  //  获取业务模式
  const getBusiness = async () => {
    const res = await apiproductBusiness();
    setProductBusiness(res);
  };
  const onCreate = () => {
    setStoreInfo({});
    setVisible(true);
    getBusiness();
  };

  const onShowInfo = (info, val) => {
    setStoreInfo(info);
    const value = val !== 'edit';
    setStatus(value);
    setVisible(true);
    getBusiness();
  };

  // 获取市区街道
  const loadData = async selectedOptions => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const res = await apiAddrArea({
      parentId: targetOption.value,
    });
    if (res) {
      const children = res.map(item => ({
        isLeaf: +item.addrLevel === 4,
        loading: false,
        label: item.addrName,
        value: item.addrId,
      }));
      targetOption.loading = false;
      if (children.length > 0) {
        targetOption.children = children;
      } else {
        targetOption.isLeaf = true;
        if (selectedOptions.length === 3) {
          divDom.current.blur();
        }
      }
      setAreaAddr([...areaAddr]);
    }
  };
  const getAreaAddr = async id => {
    const params = {};
    if (id) {
      params.parentId = id;
    }
    const res = await apiAddrArea(params);
    if (res) {
      const arr = res.map(item => ({
        isLeaf: false,
        loading: false,
        label: item.addrName,
        value: item.addrId,
      }));
      setAreaAddr(arr);
      return arr;
    }
    return [];
  };

  const getList = async (params = {}) => {
    const res = await searchList(Object.assign({ current: pageNo, pageSize }, params));
    if (res && res.data && res.data.length) {
      setDataList(res.data);
    } else {
      setDataList([]);
    }
    setTotalNum(res.total);
  };

  // 搜索
  const onSearch = async val => {
    const params = {};
    if (val.name) {
      params.name = val.name;
    }
    if (val.addr && val.addr.length) {
      const ids = ['provinceId', 'cityId', 'countyId', 'townId'];
      val.addr.forEach((item, i) => {
        params[ids[i]] = item;
      });
    }
    if (val.businessStatus) {
      params.businessStatus = val.businessStatus;
    }

    getList(params);
  };
  const closeModal = isReload => {
    if (isReload) {
      onSearch(refSearch.current?.getFieldValue?.() || {});
    }
    setStatus(false);
    setStoreInfo({});
    setVisible(false);
  };

  const enableStore = async (id, state) => {
    const enable = +state === 1 ? 0 : 1;
    const res = await apiEnableStore({ id, state: enable });
    if (res === '0000') {
      notification.success({ message: `已${state ? '禁用' : '启用'}` });
      onSearch(refSearch.current?.getFieldValue?.() || {});
    }
  };
  const onEnableState = async ({ id, state }) => {
    if (state) {
      confirm({
        title: '确认要禁用这家门店吗？',
        content: '禁用后用户将无法看到该店铺',
        onOk() {
          enableStore(id, state);
        },
      });
    } else {
      enableStore(id, state);
    }
  };

  const onReset = () => {
    if (refSearch.current && refSearch.current.resetFields) {
      refSearch.current.resetFields();
    }
    getList();
  };

  const onPageChange = (e, size) => {
    setPageNo(e);
    setPageSize(size);
    onSearch(refSearch.current?.getFieldValue?.() || {});
  };

  useEffect(() => {
    getList();
    getAreaAddr();
  }, []);

  const getWeekSlots = weekArr => {
    const htmlArr = [];
    if (weekArr && weekArr.length) {
      const arr = [];
      let brr = [];
      weekArr.reduce((prev, cur) => {
        if (prev + 1 === cur) {
          brr.push(cur);
        } else {
          arr.push(brr);
          brr = [cur];
        }
        return cur;
      }, 0);
      arr.push(brr);
      if (arr.length) {
        arr.forEach(item => {
          if (htmlArr.length) {
            htmlArr.push(',');
          }
          if (item.length > 1) {
            htmlArr.push(
              <span key={item[0]}>
                {weeks[item[0]]} ~ {weeks[item[item.length - 1]]}
              </span>,
            );
          } else {
            htmlArr.push(<span key={item[0]}>{weeks[item[0]]}</span>);
          }
        });
      }
    }
    return htmlArr;
  };

  const columns = [
    {
      title: '业务模式',
      dataIndex: 'productBusiness',
      width: 120,
      align: 'center',
      render: v => (
        <div>
          {v.map(it => (
            <span>{businessList.find(item => +it === +item.value).label}&nbsp;</span>
          ))}
        </div>
      ),
    },
    {
      title: '门店名称',
      dataIndex: 'name',
      width: 120,
      align: 'center',
    },
    {
      title: '营业状态',
      dataIndex: 'businessStatus',
      width: 80,
      align: 'center',
      render: val => businessStatus.find(item => item.value === val)?.label || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 120,
      align: 'center',
    },
    {
      title: '门店电话',
      dataIndex: 'phone',
      align: 'center',
      width: 100,
    },
    {
      title: '门店状态',
      dataIndex: 'state',
      hideInSearch: true,
      align: 'center',
      width: 80,
      render: v => <span>{`${stateDesc[v]}`}</span>,
    },
    {
      title: '操作',
      hideInSearch: true,
      dataIndex: 'action',
      width: 200,
      fixed: 'right',
      render: (val, r) => (
        <div className={style.actionBtn}>
          <Button key="look" onClick={() => onShowInfo(r)}>
            查看
          </Button>
          <Button key="seek" onClick={() => onShowInfo(r, 'edit')}>
            修改
          </Button>
          <Button key="enable1" onClick={() => onEnableState(r)} type="primary">
            {+r.state ? '禁用' : '启用'}
          </Button>
        </div>
      ),
    },
  ];
  return (
    <div>
      <div className={style.serachForm}>
        <Form {...layout} ref={refSearch} onFinish={e => onSearch(e)} name="formData">
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="门店名称" name="name">
                <Input placeholder="请输入门店名称" allowClear maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="地区" name="addr">
                <Cascader
                  ref={divDom}
                  options={areaAddr}
                  loadData={e => loadData(e)}
                  changeOnSelect
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="营业状态" name="businessStatus">
                <Select>
                  {businessStatus.map(item => (
                    <Option label={item.label} value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <div className={style.search}>
            <Button type="primary" htmlType="submit" size="middle">
              搜索
            </Button>
            <Button size="middle" className={style.searchBtn} onClick={() => onReset()}>
              重置
            </Button>
            <Button type="primary" size="middle" onClick={() => onCreate()}>
              新建
            </Button>
          </div>
        </Form>
      </div>
      <Table
        dataSource={dataList}
        bordered
        columns={columns}
        rowKey={record => record.id}
        pagination={false}
        scroll={{ x: '100%' }}
      />
      {dataList && dataList.length ? (
        <div className={style.pageBox}>
          <Pagination
            style={{ marginBottom: 10 }}
            onChange={onPageChange}
            total={totalNum}
            showTotal={total => `共${total}条`}
            current={pageNo}
            pageSize={pageSize}
            showSizeChanger
            onShowSizeChange={onPageChange}
          />
        </div>
      ) : null}
      <StoreModal
        visible={visible}
        onCancel={closeModal}
        formInfo={storeInfo}
        status={status}
        productBusiness={productBusiness}
      />
    </div>
  );
};
