import React, { useState, useEffect, useRef } from 'react';
import { Form } from '@ant-design/compatible';
import moment from 'moment';
import { PlusSquareFilled, MinusSquareFilled } from '@ant-design/icons';
import { Modal, Input, TimePicker, Checkbox, Cascader, Radio, notification, Button } from 'antd';
import { apiAddrArea, apiCreatStore, apiEditStore } from '../services';
import { weekOptions, weekDefault, layout } from '../data';
import MapModal from '@/components/GaoDeMap';
import style from './style.less';
import { isCheckNumberLine } from '@/utils/validator';
import Upload from '../../components/upload';

const FormItem = Form.Item;

const StoreModal = props => {
  const {
    visible,
    onCancel,
    form: { getFieldDecorator, setFieldsValue, getFieldsValue, validateFields, resetFields },
    formInfo,
    status,
    productBusiness,
    existTakewayShop,
  } = props;
  const [areaAddr, setAreaAddr] = useState([]);
  const [visibleMap, setVisibleMap] = useState(false);
  const [times, setTimes] = useState([{ name: 'time0' }]);
  const [formData, setFormData] = useState({});
  const [mapInfo, setMapInfo] = useState({
    provice: '',
    address: '',
  });
  const [disabled, setDisabled] = useState(false);
  const [isDisabled, setIsDisabled] = useState(false);
  const [businessModel, setBusinessModel] = useState([
    { label: $t('food.delivery.service'), value: 1 },
    { label: $t('physical.goods.sales'), value: 2 },
    { label: $t('instore.service.service.business'), value: 3 },
  ]);
  const divDom = useRef();

  const handleCancel = isSuccess => {
    resetFields();
    onCancel(isSuccess);
  };

  const onSubmit = () => {
    validateFields(async (error, fieldsValue) => {
      if (!error) {
        const params = Object.assign({}, formInfo, fieldsValue);
        const areaArr = ['provinceId', 'cityId', 'countyId', 'townId'];
        if (params.addr && params.addr.forEach) {
          params.addr.forEach((item, i) => {
            params[areaArr[i]] = item;
          });
        }
        if (params?.shopHeadImage?.length) {
          // eslint-disable-next-line prefer-destructuring
          params.shopHeadImage = params.shopHeadImage[0];
        }
        if (params.lnglat) {
          const arr = params.lnglat.split(',');
          if (arr.length === 2) {
            params.longitude = arr[0] || '';
            params.latitude = arr[1] || '';
          }
        }
        const hoursItems = [];
        if (times && times.length && times.forEach) {
          times.forEach(item => {
            hoursItems.push({
              begin: moment(params[item.name][0]).format('HH:mm'),
              end: moment(params[item.name][1]).format('HH:mm'),
            });
          });
        }
        params.businessHours = {
          weeks: params.week,
          hoursItems,
        };
        let api = apiCreatStore;
        if (params.id) {
          api = apiEditStore;
        }
        const res = await api(params);
        if (res === '0000') {
          notification.success({ message: $t('saved.successfully') });
          handleCancel(true);
        }
      }
    });
  };

  const getAreas = arr => {
    let areas = areaAddr;
    let addr = '';
    arr.forEach(c => {
      let index = 0;
      areas.forEach((item, i) => {
        if (item.value === c) {
          addr += item.label;
          index = i;
        }
      });
      areas = areas[index].children;
    });
    return addr;
  };

  // 显示地图
  const openMap = v => {
    const values = getFieldsValue();
    let provice = $t('beijing');
    if (!values.addr) {
      notification.warning({ message: $t('select.store.area.first') });
      return;
    }

    if (!values.address) {
      notification.warning({ message: $t('complete.full.address.first') });
      return;
    }
    if (values.addr.length > 0) {
      areaAddr.forEach(item => {
        if (item.value === values.addr[0]) {
          provice = item.label;
        }
      });
    }
    const labels = getAreas(values.addr);
    setMapInfo({
      provice,
      address: labels + values.address,
    });
    setVisibleMap(v);
  };

  // 获取地址省
  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 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 onTimePlus = () => {
    times.push({
      name: `time${times.length}`,
    });
    setTimes([...times]);
  };
  const onTimeMinus = i => {
    times.splice(i, 1);
    setTimes([...times]);
  };

  const onSetPoint = e => {
    setFieldsValue({
      lnglat: e,
    });
  };

  const getLazyAddr = async info => {
    const arr = await getAreaAddr();
    const parr = arr.filter(item => +item.value === +info.provinceId);
    parr[0].children = await getAreaAddr(parr[0].value);
    const carr = parr[0].children.filter(item => +item.value === +info.cityId);
    carr[0].children = await getAreaAddr(carr[0].value);
    if (info.townId) {
      const aarr = carr[0].children.filter(item => +item.value === +info.countyId);
      aarr[0].children = await getAreaAddr(aarr[0].value);
    }
    setAreaAddr([...arr]);
  };

  const normFile = fileList => fileList;

  const timerWrapper = async (time, timeString, callback) => {
    if (timeString && timeString.length) {
      const begin = moment(timeString[0]).format('HH:mm');
      const end = moment(timeString[1]).format('HH:mm');
      if (begin === end) {
        callback(new Error($t('startend.time.mismatch')));
      }
    } else {
      callback();
    }
  };

  const onBusiness = e => {
    const val = e.includes(1);
    setIsDisabled(val);
  };
  useEffect(() => {
    if (visible) {
      resetFields();
      const info = Object.assign({}, formInfo);
      const val = info?.productBusiness?.includes(1);
      setIsDisabled(val);
      if (status === 'look') {
        setDisabled(true);
      } else {
        setDisabled(false);
      }
      const data = [...businessModel];
      data.forEach(item => {
        item.disabled = !productBusiness.includes(item.value);
        if (existTakewayShop && item.value === 1 && !val) {
          item.disabled = true;
        }
      });
      console.log(data, '.........');
      setBusinessModel(data);
      if (info && info.id) {
        info.week = info.businessHours.weeks;
        const hours = info.businessHours.hoursItems;
        const harr = [];
        if (hours && hours.length) {
          hours.forEach((item, i) => {
            info[`time${i}`] = [moment(item.begin, 'HH:mm'), moment(item.end, 'HH:mm')];
            harr.push({
              name: `time${i}`,
            });
          });
        }

        info.lnglat = `${info.longitude},${info.latitude}`;
        info.addr = [info.provinceId, info.cityId, info.countyId];
        info.shopHeadImage = (info.shopHeadImage && [info.shopHeadImage]) || [];
        if (info.townId) {
          info.addr.push(info.townId);
        }
        setTimes(harr);
        setFormData(info);
        getLazyAddr(info);
      } else {
        if (areaAddr.length < 1) {
          getAreaAddr();
        }
        setFormData({});
      }
    }
  }, [visible]);

  return (
    <Modal
      title={$t('store.info')}
      visible={visible}
      width="1000px"
      destroyOnClose
      maskClosable={false}
      onCancel={() => handleCancel()}
      footer={
        <>
          <Button key="back" onClick={() => handleCancel()}>{$t('cancel')}</Button>
          {!disabled && (
            <Button key="submit" type="primary" onClick={() => onSubmit()}>{$t('confirm')}</Button>
          )}
        </>
      }
    >
      <Form {...layout} name="formData">
        <FormItem label={$t('business.model')}>
          {getFieldDecorator('productBusiness', {
            rules: [{ required: true, message: $t('select.business.model') }],
            initialValue: formData.productBusiness,
          })(<Checkbox.Group disabled={disabled} options={businessModel} onChange={onBusiness} />)}
        </FormItem>
        {isDisabled && (
          <FormItem label={$t('store.avatar')}>
            {getFieldDecorator('shopHeadImage', {
              rules: [{ required: true, message: $t('upload.store.avatar') }],
              initialValue: formData.shopHeadImage || [],
              valuePropName: 'fileList',
              getValueFromEvent: normFile,
            })(<Upload max={1} accept=".jpg,.png,.jpeg" disabled={disabled} />)}
          </FormItem>
        )}
        <FormItem
          label={$t('store.name')}
          name="name"
          extra={$t('store.name.follows.format.brand.location.eg.uniqlo.sanlitun')}
        >
          {getFieldDecorator('name', {
            rules: [{ required: true, message: $t('store.name.required') }],
            initialValue: formData.name,
          })(<Input placeholder={$t('enter.store.name')} allowClear maxLength={20} disabled={disabled} />)}
        </FormItem>
        <FormItem label={$t('store.phone')} name="phone">
          {getFieldDecorator('phone', {
            rules: [
              { required: true, message: $t('store.phone.required') },
              { validator: isCheckNumberLine, message: $t('enter.store.phone') },
            ],
            initialValue: formData.phone,
          })(<Input placeholder={$t('enter.store.phone')} allowClear maxLength={20} disabled={disabled} />)}
        </FormItem>
        <FormItem label={$t('business.hours')} required>
          {times &&
            times.map((item, i) => (
              <div className={style.timerWrapper} key={item.name}>
                <div>
                  <FormItem name={item.name}>
                    {getFieldDecorator(item.name, {
                      rules: [
                        { required: true, message: $t('select.business.hours') },
                        { validator: timerWrapper, message: $t('startend.time.mismatch') },
                      ],
                      initialValue: formData[item.name],
                    })(<TimePicker.RangePicker format="HH:mm" disabled={disabled} />)}
                  </FormItem>
                </div>
                {!disabled &&
                  (i > 0 ? (
                    <div className={style.timerWrapperRight} onClick={() => onTimeMinus(i)}>
                      <MinusSquareFilled
                        style={{ color: '#ff4d4f', fontSize: '30px' }}
                        disabled={disabled}
                      />
                    </div>
                  ) : (
                    <div className={style.timerWrapperRight} onClick={() => onTimePlus()}>
                      <PlusSquareFilled
                        style={{ color: '#1890ff', fontSize: '30px' }}
                        disabled={disabled}
                      />
                    </div>
                  ))}
              </div>
            ))}
        </FormItem>
        <FormItem label={$t('business.day')}>
          {getFieldDecorator('week', {
            rules: [{ required: true, message: $t('select.business.days') }],
            initialValue: formData.week || weekDefault,
          })(<Checkbox.Group options={weekOptions} disabled={disabled} />)}
        </FormItem>
        <FormItem label={$t('store.region')}>
          {getFieldDecorator('addr', {
            rules: [{ required: true, type: 'array', message: $t('store.area.required') }],
            initialValue: formData.addr,
          })(
            <Cascader
              ref={divDom}
              options={areaAddr}
              placeholder={$t('select.store.area')}
              loadData={e => loadData(e)}
              changeOnSelect
              disabled={disabled}
            />,
          )}
        </FormItem>
        <FormItem label={$t('full.address')}>
          {getFieldDecorator('address', {
            rules: [{ required: true, message: $t('enter.full.address') }],
            initialValue: formData.address,
          })(
            <Input
              placeholder={$t('detailed.address.excl.region')}
              allowClear
              maxLength={50}
              disabled={disabled}
            />,
          )}
        </FormItem>
        <FormItem label={$t('coordinates')}>
          {getFieldDecorator('lnglat', {
            rules: [{ required: true, message: $t('coordinates.required') }],
            initialValue: formData.lnglat,
          })(
            <Input
              placeholder={$t('select.coordinates')}
              readOnly
              onClick={() => openMap(true)}
              maxLength={100}
              disabled={disabled}
            />,
          )}
        </FormItem>
        <FormItem label={$t('enable.or.not')}>
          {getFieldDecorator('state', {
            rules: [{ required: true, message: $t('select.enabledisable') }],
            initialValue: formData.state,
          })(
            <Radio.Group disabled={disabled}>
              <Radio value={1}>{$t('yes')}</Radio>
              <Radio value={0}>{$t('no')}</Radio>
            </Radio.Group>,
          )}
        </FormItem>
        {isDisabled && (
          <FormItem label={$t('store.notice')}>
            {getFieldDecorator('publicNotice', {
              initialValue: formData.publicNotice,
            })(<Input placeholder={$t('enter.store.notice')} maxLength={120} disabled={disabled} />)}
          </FormItem>
        )}
      </Form>
      <MapModal
        visible={visibleMap}
        addrInfo={mapInfo}
        onCancel={() => openMap(false)}
        onSetPoint={e => onSetPoint(e)}
      ></MapModal>
    </Modal>
  );
};

export default Form.create()(StoreModal);
