import {
  Button,
  Cascader,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Popconfirm,
  Select,
  Table,
} from "antd";
import { PlusOutlined, CloseCircleOutlined } from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import classNames from "classnames";
import "./index.css";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import ImageLazy from "../ImageLazy";
const { Option } = Select;

type Props = {
  id: any;
  colsePage: any;
};

function ObjectAdd({ id, colsePage }: Props) {
  const dispatch = useDispatch();

  // 没有通过校验
  const onFinishFailed = () => {
    setTitSelect("tit1");
    return message.warning("有表单不符号规则!");
  };
  // 通过校验之后发送请求
  const onFinish = async (values: any) => {
    console.log("具体质量的单位", danweiValue);

    console.log("--点击确定存到仓库", values);
  };

  // 选择商品信息还是附近（默认商品信息）
  const [titSelect, setTitSelect] = useState("tit1");

  // 从仓库中获取各下拉数据
  const options1 = useSelector(
    (state: RootState) => state.loginStore.selectAll["藏品编号名称"]
  );

  const options2 = useSelector(
    (state: RootState) => state.loginStore.selectAll["年代"]
  );
  const options3 = useSelector(
    (state: RootState) => state.loginStore.selectAll["质地"]
  );
  const options4 = useSelector(
    (state: RootState) => state.loginStore.selectAll["文物类别"]
  );
  const options5 = useSelector(
    (state: RootState) => state.loginStore.selectAll["文物级别"]
  );
  const options6 = useSelector(
    (state: RootState) => state.loginStore.selectAll["质量范围"]
  );
  const options7 = useSelector(
    (state: RootState) => state.loginStore.selectAll["完残程度"]
  );
  const options8 = useSelector(
    (state: RootState) => state.loginStore.selectAll["保存状态"]
  );
  const options9 = useSelector(
    (state: RootState) => state.loginStore.selectAll["入藏时间范围"]
  );

  // 单位选择
  const [danweiValue, setDanweiValue] = useState("kg");

  // 设置表单初始数据（区分编辑和新增）

  const defaultData = useRef<any>(null);
  if (id) {
    defaultData.current = {
      name1: "编辑",
      name3: "索书号",
      name5: ["其他"],
    };
  } else {
    defaultData.current = {
      name3: options1[0].name ? options1[0].name : null,
      name5: ["地质年代", "显生宙", "新生代", "第四纪"],
      name6: ["单一质地", "有机质", "竹"],
      name8: options4[0].name ? options4[0].name : null,
      name10: options5[0].name ? options5[0].name : null,
      name15: options6[0].name ? options6[0].name : null,
      name17: options7[0].name ? options7[0].name : null,
      name19: options9[0].name ? options9[0].name : null,
    };
  }

  // -----------关于藏品附件的信息
  const [fileSelect, setFileSelect] = useState("img");

  const fileSelectChangeFu = (value: string) => {
    setFileSelect(value);
  };

  // 表格数据
  useEffect(() => {
    dispatch({
      type: "login/setFileData",
      payload: {
        img: [
          {
            id: 1,
            name: "图片1",
            time: "2022-12-13",
            img: "https://ts1.cn.mm.bing.net/th/id/R-C.6d2d3fecd79a96e43d1a410640d7199b?rik=B7RCgF82Vb7P0A&riu=http%3a%2f%2f5b0988e595225.cdn.sohucs.com%2fimages%2f20190831%2f3e03e9c2473c40b180aa99a37c0589fa.jpeg&ehk=JXdgMrjnolHlMkdX9N0K7%2fzBc9wi7FSFDjSGclreQbI%3d&risl=&pid=ImgRaw&r=0",
          },
          {
            id: 2,
            name: "图片2",
            time: "2022-12-14",
            img: "",
          },
          {
            id: 3,
            name: "图片3",
            time: "2022-12-14",
            img: "",
          },
        ],
        video: [
          {
            id: 4,
            name: "视频1",
            time: "2022-12-14",
            img: "",
          },
        ],
        audio: [],
      },
    });
  }, [dispatch]);

  const results = useSelector((state: RootState) => state.loginStore.fileData);

  // 点击表格里面的删除
  const delOne = useCallback(
    (id: number) => {
      const data = {
        ...results,
        [fileSelect]: results[fileSelect].filter((v: any) => v.id !== id),
      };
      dispatch({ type: "login/setFileData", payload: data });
    },
    [dispatch, fileSelect, results]
  );

  // 表格格式
  const columns = useMemo(() => {
    const tempArr = [
      {
        title: "附件名称",
        dataIndex: "name",
      },
      {
        title: "上传时间",
        dataIndex: "time",
      },
      {
        title: "操作",
        render: (item: any) => (
          <>
            <Button type="text" danger onClick={() => upFileFu(item.id)}>
              重传
            </Button>
            <Popconfirm
              title="确定删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => delOne(item.id)}
            >
              <Button type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];

    if (fileSelect === "img") {
      tempArr.unshift({
        title: "缩略图",
        render: (item: any) => (
          <div className="tableImg">
            <ImageLazy width={120} height={70} src={item.img} />
          </div>
        ),
      });
    }

    return tempArr;
  }, [delOne, fileSelect]);

  const [cover, setCover] = useState(
    "http://project.4dage.com:8016/content/1_1001/img/20220810_1553241331042.JPG"
  );

  const fileSelectList = useMemo(() => {
    return [
      { id: 1, value: "img", label: "高清图片" },
      { id: 2, value: "video", label: "视频文件" },
      { id: 3, value: "audio", label: "音频文件" },
      { id: 4, value: "model", label: "三维模型" },
      { id: 5, value: "file", label: "文档资料" },
    ];
  }, []);

  // 上传封面
  const myInput = useRef<HTMLInputElement>(null);
  const handeUpPhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      // 拿到files信息
      const filesInfo = e.target.files[0];
      // 校验格式
      const type = ["image/jpeg", "image/png"];
      if (!type.includes(filesInfo.type)) {
        e.target.value = "";
        return message.warning("只支持jpg、png格式!");
      }
      // 校验大小
      if (filesInfo.size > 10 * 1024 * 1024) {
        e.target.value = "";
        return message.warning("最大支持10M!");
      }

      // 测试代码
      console.log("-------", filesInfo);

      // 创建FormData对象
      const fd = new FormData();
      // 把files添加进FormData对象（‘photo’为后端需要的字段）
      fd.append("file", filesInfo);
      // fd.append("type", "img");
    }
  };

  // 上传附件
  const myInput2 = useRef<HTMLInputElement>(null);

  const upFileFlagRef = useRef(false);

  const upFileFu = (flag?: any) => {
    upFileFlagRef.current = flag ? flag : 0;
    myInput2.current?.click();
  };
  const handeUpPhoto2 = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0];

        // 创建FormData对象
        const fd = new FormData();
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        fd.append("file", filesInfo);
        // fd.append("type", "img");

        e.target.value = "";
        if (upFileFlagRef.current) {
          console.log("重新上传", upFileFlagRef.current);

          const id = upFileFlagRef.current;
          const data = {
            ...results,
            [fileSelect]: results[fileSelect].map((v: any) => {
              if (id !== v.id) return v;
              else
                return {
                  id: 10,
                  name: "9999",
                  time: "2022-12-14",
                  img: "",
                };
            }),
          };
          dispatch({ type: "login/setFileData", payload: data });
        } else {
          console.log("新上传");
        }
      }
    },
    [dispatch, fileSelect, results]
  );

  return (
    <div className={styles.ObjectAdd}>
      <Modal
        wrapClassName="ObjectAdd"
        destroyOnClose
        open={true}
        title={id ? "编辑藏品" : "添加藏品"}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        {/* 商品信息和附件切换 */}
        <div className="ObjectAddTit">
          <div
            onClick={() => setTitSelect("tit1")}
            className={classNames(titSelect === "tit1" ? "active" : "")}
          >
            商品信息
          </div>
          <div
            onClick={() => setTitSelect("tit2")}
            className={classNames(
              "ObjectAddTitTow",
              titSelect === "tit2" ? "active" : ""
            )}
          >
            附件
          </div>
        </div>

        <Form
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          initialValues={defaultData.current}
        >
          {/* -----------------------表单信息 */}
          <div className="formBox" hidden={titSelect === "tit2"}>
            {/* 藏品名称----------原名 */}
            <div className="formRow">
              <Form.Item
                label="藏品名称"
                name="name1"
                rules={[{ required: true, message: "不能为空!" }]}
              >
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
              <Form.Item label="原名" name="name2">
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
            </div>
            {/* 藏品编号名称----------藏品编号 */}
            <div className="formRow">
              <div className="bs">*</div>
              <Form.Item label="藏品编号名称" name="name3">
                <Select
                  placeholder="请选择"
                  options={options1.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
              <Form.Item label="藏品编号" name="name4">
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
            </div>
            {/* 年代----------文物质地 */}
            <div className="formRow">
              <div className="bs bs2">*</div>
              <div className="bs bs3">*</div>
              <Form.Item label="年代" name="name5">
                <Cascader
                  allowClear={false}
                  fieldNames={{
                    label: "name",
                    value: "name",
                    children: "children",
                  }}
                  options={options2}
                  placeholder="请选择"
                />
              </Form.Item>
              <Form.Item label="文物质地" name="name6">
                <Cascader
                  allowClear={false}
                  fieldNames={{
                    label: "name",
                    value: "name",
                    children: "children",
                  }}
                  options={options3}
                  placeholder="请选择"
                />
              </Form.Item>
            </div>
            {/* 具体年代----------文物类别 */}
            <div className="formRow">
              <div className="bs bs3">*</div>
              <Form.Item label="具体年代" name="name7">
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
              <Form.Item label="文物类别" name="name8">
                <Select
                  placeholder="请选择"
                  options={options4.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
            </div>
            {/* 实际数量----------文物级别 */}
            <div className="formRow">
              <div className="bs bs3">*</div>
              <Form.Item
                rules={[{ required: true, message: "不能为空!" }]}
                label="实际数量"
                name="name9"
              >
                <InputNumber min={1} maxLength={8} placeholder="请输入数字" />
              </Form.Item>
              <Form.Item label="文物级别" name="name10">
                <Select
                  placeholder="请选择"
                  options={options5.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
            </div>
            {/* 外形尺寸----------通长，宽，高 */}
            <div className="formRow formRowThree">
              <Form.Item
                rules={[{ required: true, message: "不能为空!" }]}
                label="外形尺寸"
                name="name11"
              >
                <InputNumber
                  min={1}
                  maxLength={8}
                  placeholder="通长"
                  addonAfter="cm"
                />
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: "不能为空!" }]}
                label=""
                name="name12"
              >
                <InputNumber
                  min={1}
                  maxLength={8}
                  placeholder="通宽"
                  addonAfter="cm"
                />
              </Form.Item>
              <Form.Item
                className="formRowThreeRow"
                rules={[{ required: true, message: "不能为空!" }]}
                label=""
                name="name13"
              >
                <InputNumber
                  min={1}
                  maxLength={8}
                  placeholder="通高"
                  addonAfter="cm"
                />
              </Form.Item>
            </div>
            {/* 具体尺寸*/}
            <div className="formRow formRowFull">
              <Form.Item
                label="具体尺寸"
                name="name14"
                rules={[{ required: true, message: "不能为空!" }]}
              >
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
            </div>
            {/* 质量范围----------具体质量 */}
            <div className="formRow">
              <div className="bs bs4">*</div>
              <Form.Item label="质量范围" name="name15">
                <Select
                  placeholder="请选择"
                  options={options6.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
              <Form.Item
                className="formRowSelec"
                label="具体质量"
                name="name16"
              >
                <InputNumber
                  min={1}
                  maxLength={8}
                  placeholder="请输入"
                  addonAfter={
                    <Select
                      value={danweiValue}
                      onChange={(val) => setDanweiValue(val)}
                    >
                      <Option value="kg">kg</Option>
                      <Option value="g">g</Option>
                    </Select>
                  }
                />
                {/* <div className="formRowSelecSon">
                
              </div> */}
              </Form.Item>
            </div>
            {/* 完残程度----------保存状态 */}
            <div className="formRow">
              <div className="bs bs4">*</div>
              <Form.Item label="完残程度" name="name17">
                <Select
                  placeholder="请选择"
                  options={options7.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
              <Form.Item label="保存状态" name="name18">
                <Select
                  placeholder="请选择"
                  options={options8.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
            </div>
            {/* 入藏时间范围----------入藏年度 */}
            <div className="formRow">
              <div className="bs">*</div>
              <Form.Item label="入藏时间范围" name="name19">
                <Select
                  placeholder="请选择"
                  options={options9.map((v: any) => ({
                    label: v.name,
                    value: v.name,
                  }))}
                />
              </Form.Item>
              <Form.Item label="入藏年度" name="name20">
                <InputNumber
                  min={1000}
                  maxLength={4}
                  placeholder="请输入数字"
                />
              </Form.Item>
            </div>
            {/* 著者----------版本 */}
            <div className="formRow">
              <Form.Item label="著者" name="name21">
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
              <Form.Item label="版本" name="name22">
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
            </div>
            {/* 存卷*/}
            <div className="formRow formRowFull">
              <Form.Item label="存卷" name="name23">
                <Input maxLength={50} showCount placeholder="请输入" />
              </Form.Item>
            </div>
            {/* 来源说明*/}
            <div className="formRow formRowFull">
              <Form.Item label="来源说明" name="name24">
                <TextArea
                  rows={3}
                  placeholder="请输入"
                  showCount
                  maxLength={255}
                />
              </Form.Item>
            </div>
          </div>
          {/* -----------------------附件信息 */}
          <div hidden={titSelect === "tit1"}>
            <div className="fileBox">
              {/* 封面上传 */}
              <div className="fileBoxRow">
                <div className="fileBoxRow_tit">藏品图片：</div>
                <div className="fileBoxRow_r">
                  <div
                    hidden={cover !== ""}
                    className="fileBoxRow_up"
                    onClick={() => myInput.current?.click()}
                  >
                    <PlusOutlined />
                    <input
                      type="file"
                      accept=".png,.jpg"
                      ref={myInput}
                      onChange={(e) => handeUpPhoto(e)}
                    />
                  </div>
                  <div className="fileBoxRow_r_img" hidden={cover === ""}>
                    <ImageLazy width={120} height={120} src={cover} />
                    <Popconfirm
                      title="确定删除吗?"
                      okText="确定"
                      cancelText="取消"
                      onConfirm={() => setCover("")}
                    >
                      <div className="clearCover">
                        <CloseCircleOutlined />
                      </div>
                    </Popconfirm>
                  </div>
                  <div className="fileBoxRow_r_tit">
                    支持上传jpg，png格式，大小&lt;10M
                  </div>
                </div>
              </div>
              {/* 附件上传 */}
              <div className="fileBoxRow">
                <div className="fileBoxRow_tit">上传附件：</div>
                <div className="fileBoxRow_r">
                  <input
                    type="file"
                    ref={myInput2}
                    onChange={(e) => handeUpPhoto2(e)}
                  />
                  <Select
                    style={{ width: 150 }}
                    value={fileSelect}
                    onChange={fileSelectChangeFu}
                    options={fileSelectList}
                  />
                  &emsp;
                  <Button onClick={() => upFileFu()}>上传附件</Button>
                </div>
              </div>
              {/* 表格主体 */}
              <div className="addTableBox_table">
                <Table
                  scroll={{ y: 300 }}
                  dataSource={results[fileSelect]}
                  columns={columns}
                  rowKey="id"
                  pagination={false}
                />
              </div>
            </div>
          </div>

          <br />
          <Form.Item wrapperCol={{ offset: 20 }}>
            <Button onClick={colsePage}>取消</Button>
            &emsp;
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

const MemoObjectAdd = React.memo(ObjectAdd);

export default MemoObjectAdd;
