import React, { useEffect, useState } from "react";
import {
  Modal,
  Form,
  Select,
  Input,
  Row,
  Col,
  Upload,
  Transfer,
  TimePicker,
  DatePicker,
  Checkbox,
  message,
  Radio,
  Cascader,
} from "antd";
import ajax from "@/services";
import moment from "moment";
import { PlusOutlined } from "@ant-design/icons";
import { ImgUpload, TreeSelectGroup, SelectLntLat } from "@/components";
function AddParking(props) {
  const [form] = Form.useForm();
  const {
    visible = false,
    close = () => {},
    record = {},
    status = "add",
    search = () => {},
  } = props;
  //区域的下拉数据
  const [areaList, setAreaList] = useState([]);
  const [fileList, setFileList] = useState(() => {
    if (status === "add") return [];
    else {
      return [
        {
          uid: "-1",
          name: "image.png",
          status: "done",
          url: record.img,
        },
      ];
    }
  });
  const [lngLatVisible, setLngLatVisible] = useState(false);
  const [lngLat, setLngLat] = useState(() => {
    if (status === "add") return [];
    else {
      return record.lng_lat.split(",");
    }
  });
  //所属商户
  const [getOperationName, setGetOperationName] = useState([]);
  //所属商圈
  const [tradingArea, setTradingArea] = useState([]);
  //选择的商圈
  const [targetKeys, setTargetKeys] = useState([]);
  //上级路段下拉菜单
  const [parentRoadList, setParentRoadList] = useState([]);
  //父车场数据
  const [parentRoad, setParentRoad] = useState([]);
  //选择关联车场后不可选择
  const [disabled, setDisabled] = useState(false);
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  function getAreaList() {
    ajax
      .getAreaTree()
      .then((res) => {
        if (res.status === 20000) {
          setAreaList(res.data);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }
  //getParentRoadList 获取上级路段下拉
  const getParentRoadList = (type) => {
    ajax.getParentRoadList({ road_type: type }).then((res) => {
      if (res.status === 20000) {
        setParentRoadList(res.data);
      }
    });
  };
  const handleChange = ({ fileList: newFileList }) => setFileList(newFileList);

  const transferChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys);
  };
  function cascaderChange(value, options) {
    let last = options[options.length - 1];
    let res = [];
    if (last.children) {
      addChild(last, res);
    }
    res.push(last.id);
    // setAreaId(res);
  }

  //获取所属商户
  const operationName = () => {
    ajax.getAllOperator().then((res) => {
      if (res.status === 20000) {
        setGetOperationName(res.data);
      }
    });
  };
  //获取商圈数据
  const getTradingArea = () => {
    ajax.getTradingArea().then((res) => {
      if (res.status === 20000) {
        setTradingArea(
          res.data.map((item) => {
            item.key = item.value;
            return item;
          })
        );
      }
    });
  };

  const addChild = (child, res) => {
    if (child.children) {
      child.children.forEach((item) => {
        addChild(item, res);
      });
    } else {
      res.push(child.id);
    }
  };
  //获取父级路段信息
  const getParentRoadDetail = (id) => {
    ajax.getOrpRoadInfo({ id }).then((res) => {
      if (res.status === 20000) {
        setParentRoad(res.data);
        const {
          trading_area,
          operator_id,
          poi,
          address,
          is_business,
          cooperate_type,
          access_type,
          lng_lat,
        } = res.data;
        form.setFieldsValue({
          trading_area,
          operator_id,
          poi,
          address,
          is_business,
          cooperate_type,
          access_type,
        });
        setLngLat(lng_lat.split(","));
      }
    });
  };

  //处理提交图片的函数
  function processImgData(value) {
    let data = [];
    value.forEach((item) => {
      if (item.response) {
        data.push(item.response.data);
      } else {
        data.push(item.url);
      }
    });
    return data;
  }
  //新增配置信息接口
  function addOutSegmentRoad(params) {
    ajax.addOutSegmentRoad(params).then((res) => {
      if (res.status === 20000) {
        message.success("添加成功");
        close();
      } else {
        message.error(res.message);
      }
    });
  }
  //编辑配置信息接口
  function editOutSegmentRoad(params) {
    ajax.editOutSegmentRoad(params).then((res) => {
      if (res.status === 20000) {
        message.success("编辑成功");
        close();
      } else {
        message.error(res.message);
      }
    });
  }
  //提交接口
  function submit() {
    form
      .validateFields()
      .then((values) => {
        console.log(11111111,values.filings_time,values.filings_time.format('YYYY-MM-DD'),record);
        let arrStr =values.area_id
        let arr = arrStr[arrStr.length-1]
        const params = {
          ...values,
          img: processImgData(fileList),
          lng_lat: lngLat.join(","),
          open_time: [
            moment(values.open_begin_time).format("HH:mm:ss"),
            moment(values.open_end_time ).format("HH:mm:ss"),
            // record.open_begin_time,
            // record.open_end_time 
          ],
          filings_time:moment(values.filings_time).format("YY-MM-DD"),
          area_id:arr
        };
        console.log(values);
        if (status === "add") {
          addOutSegmentRoad(params);
        } else {
          editOutSegmentRoad(params);
        }
      })
      .catch((err) => console.error(err));
  }

  useEffect(() => {
    getAreaList();
    operationName();
    getTradingArea();
  }, []);

  return (
    <Modal
      width={1200}
      open={visible}
      onCancel={close}
      destroyOnClose
      title="添加封闭停车场"
      okText={"提交"}
      onOk={submit}
    >
      <Form
        form={form}
        labelCol={{ span: 8 }}
        colon={false}
        initialValues={
          status === "edit"
            ? {
                ...record,
                open_time: [
                  moment(record.open_begin_time, "HH:mm:ss"),
                  moment(record.open_end_time, "HH:mm:ss"),
                ],
                filings_time: moment(record.filings_time),
                area_id: record.area,
              }
            : {}
        }
      >
        <Row gutter={[30]}>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="停车场类型"
              rules={[{ required: true }]}
              name="road_type"
            >
              <Select
                options={sysConfig.orpRoadType}
                disabled={status === "edit"}
                onChange={(value) => {
                  console.log(value);
                  getParentRoadList(value);
                  if (value === 0 || value === 1) {
                    setDisabled(false);
                  }
                }}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="停车场系统类型"
              rules={[{ required: true }]}
              name="system_type"
            >
              <Select options={sysConfig.orpSystemType} />
            </Form.Item>
          </Col>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, curValues) =>
              prevValues.road_type !== curValues.road_type
            }
          >
            {({ getFieldValue }) => {
              const type = getFieldValue("road_type");
              console.log(type);
              if (type !== 0 && type !== 1) {
                return (
                  <Col span="4_8" style={{ width: "33%" }}>
                    <Form.Item label="关联停车场">
                      <Select
                        options={parentRoadList}
                        onChange={(value) => {
                          getParentRoadDetail(value);
                          if (value) {
                            setDisabled(true);
                          }
                        }}
                      />
                    </Form.Item>
                  </Col>
                );
              } else {
                return null;
              }
            }}
          </Form.Item>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="停车场名称"
              rules={[{ required: true }]}
              name="road_name"
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="停车场编码"
              rules={[{ required: true }]}
              name="road_code"
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="停车场物理类型"
              rules={[{ required: true }]}
              name="physics_type"
            >
              <Select
                options={[
                  {
                    label: "地上",
                    value: 1,
                  },
                  {
                    label: "地下",
                    value: 2,
                  },
                  {
                    label: "地上地下",
                    value: 3,
                  },
                ]}
              />
            </Form.Item>
          </Col>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, curValues) =>
              prevValues.road_type !== curValues.road_type
            }
          >
            {({ getFieldValue }) => {
              const type = getFieldValue("road_type");
              let child = null;
              switch (type) {
                case 0:
                  child = (
                    <Form.Item
                      label="独立车场泊位数"
                      rules={[{ required: true }]}
                      name="berth_number"
                    >
                      <Input />
                    </Form.Item>
                  );
                  break;
                case 1:
                  return (
                    <>
                      <Col span="4_8" style={{ width: "33%" }}>
                        <Form.Item
                          label="总泊位数"
                          rules={[{ required: true }]}
                          name="total_berth_number"
                        >
                          <Input />
                        </Form.Item>
                      </Col>
                      <Col span="4_8" style={{ width: "33%" }}>
                        <Form.Item
                          label="一级车场泊位数"
                          rules={[{ required: true }]}
                          name="berth_number"
                        >
                          <Input />
                        </Form.Item>
                      </Col>
                    </>
                  );
                default:
                  child = (
                    <Form.Item
                      label="车场泊位数"
                      rules={[{ required: true }]}
                      name="berth_number"
                    >
                      <Input />
                    </Form.Item>
                  );
                  break;
              }
              return (
                <Col span="4_8" style={{ width: "33%" }}>
                  {child}
                </Col>
              );
            }}
          </Form.Item>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item label="区域" rules={[{ required: true }]} name="area_id">
              <Cascader
                // onChange={cascaderChange}
                options={areaList}
                placeholder="请选择区域"
                expandTrigger="hover"
                changeOnSelect
                fieldNames={{
                  label: "name",
                  value: "id",
                  children: "children",
                }}
              />
            </Form.Item>
          </Col>
          <Col span={24} offset={1} style={{ width: "33%" }}>
            <Form.Item
              labelAlign="center"
              labelCol={{ span: 2 }}
              label="所属热门商圈"
              name="trading_area"
            >
              <Transfer
                dataSource={tradingArea}
                titles={["未选择", "已选择"]}
                showSearch={true}
                targetKeys={targetKeys}
                onChange={transferChange}
                render={(item) => item.label}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="所属商户"
              rules={[{ required: true }]}
              name="operator_id"
            >
              <Select
                options={getOperationName}
                disabled={status === "edit" || disabled}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item label="经纬度" required>
              <Input.Group>
                <Row>
                  <Col span={19}>
                    <Input value={lngLat} disabled={disabled} />
                  </Col>
                  <Col span={5}>
                    <SelectLntLat
                      open={() => setLngLatVisible(true)}
                      lngLatVisible={lngLatVisible}
                      getLntLat={(value) => {
                        setLngLat(value);
                      }}
                      disabled={disabled}
                      onChange={(address) => {
                        form.setFieldValue("address", address);
                      }}
                      close={() => setLngLatVisible(false)}
                    />
                  </Col>
                </Row>
              </Input.Group>
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item label="高德POI" name="poi">
              <Input disabled={disabled} />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item label="地址" rules={[{ required: true }]} name="address">
              <Input disabled />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="是否商业车场"
              rules={[{ required: true }]}
              name="is_business"
            >
              <Select options={sysConfig.businessRoad} disabled={disabled} />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="是否承包"
              rules={[{ required: true }]}
              name="is_contract"
            >
              <Radio.Group
                options={[
                  {
                    label: "是",
                    value: 1,
                  },
                  {
                    label: "否",
                    value: 0,
                  },
                ]}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="合作模式"
              rules={[{ required: true }]}
              name="cooperate_type"
            >
              <Select
                options={sysConfig.cooperationModel}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="停车场开放时间"
              rules={[{ required: true }]}
              name="open_time"
            >
              <TimePicker.RangePicker />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="商用状态"
              rules={[{ required: true }]}
              name="operator_status"
            >
              <Select options={sysConfig.operatorStatus} />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="车场状态"
              rules={[{ required: true }]}
              name="status"
            >
              <Select options={sysConfig.orpRoadStatus} />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="是否支持充电"
              rules={[{ required: true }]}
              name="recharge"
            >
              <Radio.Group
                options={[
                  {
                    label: "是",
                    value: 1,
                  },
                  {
                    label: "否",
                    value: 0,
                  },
                ]}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="是否支持欠费离场"
              rules={[{ required: true }]}
              name="is_arrearage"
            >
              <Radio.Group
                options={[
                  {
                    label: "是",
                    value: 1,
                  },
                  {
                    label: "否",
                    value: 0,
                  },
                ]}
              />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }}>
            <Form.Item
              label="接入方式"
              rules={[{ required: true }]}
              name="access_type"
            >
              <Select options={sysConfig.accessType} disabled={disabled} />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }} name="billing_rules">
            <Form.Item label="计费规则" name="billing_rules">
              <Input />
            </Form.Item>
          </Col>
          <Col span="4_8" style={{ width: "33%" }} name="filings_time">
            <Form.Item label="备案时间" name="filings_time">
              <DatePicker  format="YYYY-MM-DD"/>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              labelAlign="center"
              labelCol={{ span: 2 }}
              label="图片"
              rules={[{ required: true }]}
              name="img"
            >
              <Upload
                action="/PMS/api/com/common/file_upload"
                listType="picture-card"
                fileList={fileList}
                onChange={handleChange}
              >
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}

export default AddParking;
