import {
  Button,
  Space,
  Modal,
  FormInstance,
  Select,
  Popconfirm,
  PopconfirmProps,
  message,
} from "antd";
import { inject, observer } from "mobx-react";
import BTable from "@/components/b_table";
import { useEffect, useState } from "react";
import { Store } from "antd/lib/form/interface";
import SimpleForm from "@/components/form/simple_form";
import React from "react";
import { columns, defaultConfig } from "./material_column";
import { Form } from "antd";
import dayjs from "dayjs";
const { Option } = Select;
const Material = (props: Store) => {
  const { materialStore, stashStore, storageStore, materialCatStore } = props;
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [projectConfig, setProjectConfig] = useState<any>([]);
  const formRef = React.useRef<FormInstance>(null);
  const [record, setRecord] = useState<any>(null);
  const [stashList, setStash] = useState<any>(null); // 仓库列表
  const [storageList, setStorageList] = useState<any>([]); // 货架列表
  const [catList, setcatList] = useState<any>([]); // 物资分类列表
  // 获取物资列表
  useEffect(() => {
    materialStore.getlist().then(() => {
      setProjectConfig(defaultConfig);
    });
  }, [materialStore]);

  // 获取仓库列表
  useEffect(() => {
    stashStore.getlist().then(() => {
      setStash(stashStore.list);
    });
  }, [stashStore]);

  // 获取分类
  useEffect(() => {
    materialCatStore.getlist().then(() => {
      setcatList(materialCatStore.list);
    });
  }, [materialCatStore]);

  const handleChange = async (v) => {
    await storageStore.getlist({ stash_identity: v });
    setStorageList(storageStore.list ?? []);
  };
  const column_widget = (any, record) => {
    return (
      <Space wrap>
        <Button
          type="dashed"
          size="small"
          onClick={() => {
            edit(record);
          }}
        >
          编辑
        </Button>

        {/* <Button
          type="dashed"
          size="small"
          onClick={() => {
            materialStore.deleteItem(record.id);
          }}
        >
          物资出库
        </Button> */}
        <Popconfirm
          title="出库操作"
          description="请确认是否出库该物资?"
          onConfirm={() => {
            try {
              materialStore.deleteItem(record.id);
              message.success("物资出库成功");
            } catch (error) {
              message.success("物资出库失败");
            }
          }}
          onCancel={cancel}
          okText="Yes"
          cancelText="No"
        >
          <Button danger size="small">
            物资出库
          </Button>
        </Popconfirm>
        <Popconfirm
          title="删除操作"
          description="请确认是否删除物资?"
          onConfirm={() => {
            try {
              materialStore.deleteItem(record.id);
              message.success("删除成功");
            } catch (error) {
              message.success("删除失败");
            }
          }}
          onCancel={cancel}
          okText="Yes"
          cancelText="No"
        >
          <Button danger size="small">
            删除
          </Button>
        </Popconfirm>
      </Space>
    );
  };
  const edit = (record) => {
    setIsModalOpen(true);
    record.expiry_date = dayjs(record.expiry_date);
    setRecord(record);
  };

  const cancel: PopconfirmProps["onCancel"] = (e) => {
    console.log(e);
    message.error("Click on No");
  };
  const onFinish = (values: any) => {
    let data = {
      ...values,
      pid: values.pid ?? 0,
      storage_cloumn: Number(values.storage_cloumn),
      // supplie_piker: values.supplie_piker[0].name,
    };
    if (values.supplie_piker.length > 0) {
      data.supplie_piker = values.supplie_piker[0].name;
    }else{
      data.supplie_piker = ""
    }
    if (!record?.id) {
      materialStore.add(data);
    } else {
      materialStore.putItem(record.id, data);
    }
    setIsModalOpen(false);
  };

  const onFinishFailed = () => {};
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Space direction="horizontal" size={"middle"}>
          <Button
            type="default"
            onClick={() => {
              setRecord(null);
              setProjectConfig(defaultConfig);
              setIsModalOpen(true);
            }}
          >
            添加物资
          </Button>
        </Space>
        <BTable
          store={materialStore}
          columns={[
            ...columns,
            {
              title: "操作",
              dataIndex: "id",
              ellipsis: {
                showTitle: false,
              },
              render: (any, record) => column_widget(any, record),
            },
          ]}
          dataSource={materialStore.list}
        />
        <Modal
          title={!record?.id ? "添加物资" : "编辑物资"}
          width={1000}
          open={isModalOpen}
          afterClose={() => formRef.current?.resetFields()}
          onOk={() => formRef.current?.submit()}
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            setIsModalOpen(false);
          }}
        >
          <SimpleForm
            formRef={formRef}
            createCallback={() => {
              if (record?.id) {
                formRef.current?.setFieldsValue(record);
              } else {
                formRef.current?.setFieldsValue(null);
              }
            }}
            formName="card_basic"
            colProps={25}
            subBtnName="提交"
            formDatas={projectConfig}
            onFinish={onFinish}
            initialValues={true}
            onFinishFailed={onFinishFailed}
          >
            <>
              <Form.Item
                key="stash_identity"
                label="所属仓库"
                name="stash_identity"
                rules={[{ required: true, message: "请选择所属仓库!" }]}
              >
                <Select
                  placeholder=""
                  onChange={(v) => {
                    handleChange(v);
                  }}
                >
                  {stashList?.map((v: any) => {
                    return (
                      <Option key={v.identity} value={v.identity}>
                        {v.stash_name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                key="storage_identity"
                label="所属货架"
                name="storage_identity"
                rules={[{ required: true, message: "请选择所属货架!" }]}
              >
                <Select placeholder="">
                  {storageList?.map((v: any) => {
                    return (
                      <Option key={v.identity} value={v.identity}>
                        {v.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                key="catory_identity"
                label="物资分类"
                name="catory_identity"
                rules={[{ required: true, message: "请选择物资分类!" }]}
              >
                <Select placeholder="">
                  {catList?.map((v: any) => {
                    return (
                      <Option key={v.identity} value={v.identity}>
                        {v.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </>
          </SimpleForm>
        </Modal>
      </Space>
    </div>
  );
};

export default inject(
  "materialStore",
  "stashStore",
  "storageStore",
  "materialCatStore"
)(observer(Material));
