import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, Select, Cascader, Tag, notification, Tree, Col, Row } from 'antd';
import React, { useState, useEffect } from 'react';
import { el } from 'date-fns/locale';
import { areaList, getAddTemplate, forbiddenAddress } from '../services';
import CustomTree from '@/components/CustomTree';

const AddAreaModal = props => {
  const {
    visible,
    form: { getFieldDecorator, validateFields, resetFields, setFieldsValue },
    templateData,
  } = props;
  const [selectedList, setSelectedList] = useState([]);
  const [treeData, setTreeData] = useState([]);

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const filterData = arr =>
    arr.map(item => ({
      label: item.addrName,
      key: Number(item.addrId),
      level: item.addrLevel,
      children: [],
      // value: props.templateData.list.filter(item => item.)
    }));
  const loadProvice = async () => {
    const data = await areaList();
    if (data && data.length) {
      const arr = filterData(data);
      setTreeData(arr);
    }
  };

  const onCancel = () => {
    resetFields();
    props.onSubmit();
  };
  const handleOk = () => {
    validateFields(async (error, fieldsValue) => {
      const newData = [];
      const getValues = (list, level) => {
        list.forEach(itemData => {
          if (itemData.checked) {
            newData.push({
              addressId: itemData.key,
              addressLevel: itemData.level || level,
              addressName: itemData.label,
            });
          } else if (itemData.children && itemData.children.length) {
            getValues(itemData.children, level + 1);
          }
        });
      };
      if (!error) {
        console.log('fieldsValue :>> ', fieldsValue);
        getValues(fieldsValue.list, 1);
        if (props.templateData.status) {
          const data = await forbiddenAddress({
            templateId: props.templateData.id,
            templateName: fieldsValue.templateName,
            areaList: newData,
          });
          if (data.businessCode === '0000') {
            notification.success({ message: '编辑成功！' });
            onCancel();
          }
        } else {
          const data = await getAddTemplate({
            templateName: fieldsValue.templateName,
            areaList: newData,
          });
          if (data.businessCode === '0000') {
            notification.success({ message: '添加成功！' });
            onCancel();
          }
        }
      }
    });
  };
  const onLoadData = async ({ key }) => {
    const res = await areaList({ parentId: key });
    return res || [];
  };

  useEffect(() => {
    if (props.templateData) {
      let arr = [];
      const dealData = list =>
        list.map(item => {
          item.key = +item.addressId;
          item.label = item.addressName;
          item.indeterminate = !item.isForbidden;
          item.checked = item.isForbidden;
          item.children && item.children.length && dealData(item.children);
          return item;
        });
      arr = dealData(props.templateData.list || []);
      setSelectedList(arr);
    }
  }, [props.templateData]);

  useEffect(() => {
    props.visible && loadProvice();
  }, [props.visible]);

  return (
    <Modal
      title={props.templateData.status ? '编辑限制区域配送模板' : '添加限制区域配送模板'}
      maskClosable={false}
      visible={visible}
      width="800px"
      onCancel={() => onCancel()}
      onOk={() => handleOk()}
    >
      <Form {...formItemLayout}>
        <Form.Item label="模板名称">
          {getFieldDecorator('templateName', {
            rules: [{ required: true, message: '请输入模板名称!' }],
            initialValue: templateData.templateName,
          })(<Input placeholder="请填写模板名称" maxLength={20} />)}
        </Form.Item>
        <Form.Item label="限制配送区域">
          {getFieldDecorator('list', {
            rules: [{ required: true, message: '请选择限制配送区域!', type: 'array' }],
            initialValue: selectedList,
          })(<CustomTree treeData={treeData} loadData={onLoadData} valueKey="addressId" />)}
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default Form.create()(AddAreaModal);
