import {Table, Popconfirm, Divider, Modal, Input, Button, message, Form} from 'antd';
import React, {useEffect, useState} from 'react';
import useInitial from "@/hooks/useInitail";
import {getList, ListVO} from "@/pages/pms/partPlan/PlanPool/api";
import {useStore} from "@/pages/pms/partPlan/PlanPool";
import {deleteApi, editApi} from '../api';

const { Column } = Table;
const {Item} = Form;
interface Props {
  // eslint-disable-next-line react/no-unused-prop-types
  type?: number, // 类型1区域库2库房3车系4车型5配件
}
export default function Index(props: Props = {}) {
  const { dfParams, key, setItem, setOutVisible, setCustVisible } = useStore();
  const [form] = Form.useForm();
  const { data: parts, setParams, loading } = useInitial(getList, [], dfParams);
  const [visible, setVisible] = useState(false);
  const [itemPrice, setItemPrice] = useState<ListVO>();

  useEffect(() => {
    if (key == props.type) {
      setParams(dfParams, true);
    }
  }, [dfParams, key]);

  useEffect(() => {
    if (visible && itemPrice?.poolId) {
      form.setFieldsValue({ cnt: itemPrice.cnt});
    } else {
      form.resetFields;
    }
  }, [visible]);

  return (
    <div>
      <Table rowKey={(v: ListVO) => `${v.poolId}`} scroll={{y: 500, x: 3000}} dataSource={parts || []} pagination={false} loading={loading}>
        <Column title="配件编码" dataIndex="code" fixed="left" />
        <Column title="配件名称" dataIndex="name" fixed="left" />
        <Column title="本次计划数量(个)" dataIndex="cnt" fixed="left" />
        <Column
          title="操作"
          fixed="left"
          render={r => (
            <>
              <a onClick={() => { setVisible(true); setItemPrice(r); }}>编辑</a>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除?"
                onConfirm={() => {
                  deleteApi({ poolId: r.poolId }).then(res => {
                    message.success("操作成功");
                    setParams({}, true);
                  }).catch(e => message.error(e.message));
                }}
              >
                <a>删除</a>
              </Popconfirm>
            </>
          )}
        />
        <Column title="库房名称" dataIndex="storageName" />
        <Column title="门店名称" dataIndex="shopName" />
        <Column title="来源类型" dataIndex="typeName" />
        <Column title="配件类型" dataIndex="partTypeName" />
        
        <Column title="计划前库销比" dataIndex="ratio" render={t => (t || 0).toFixed(2)} />
        <Column title="计划后库销比" dataIndex="planeRatio" render={t => (t || 0).toFixed(2)} />
        
        <Column title="本次计划金额(元)" dataIndex="thisTimeAmount" />
        <Column title="客户订件数量(个)" render={r => <a onClick={() => { setCustVisible(true); setItem(r); }}>{r.buyCnt}</a>} />
        <Column title="客户订件金额(元)" dataIndex="buyAmount" />
        <Column title="在途未锁(个)" dataIndex="onTheWayUnlockCnt" />
        <Column title="在库未锁(个)" dataIndex="storageUnlockCnt" />
        <Column title="在库已锁(个)" dataIndex="storageLockedCnt" />
        <Column title="滚动90天出库(个)" render={r => <a onClick={() => { setOutVisible(true); setItem(r); }}>{r.outStockCnt}</a>} />
        
      </Table>
      <Modal
        title="编辑采购数量"
        visible={visible}
        maskClosable={false}
        onCancel={() => setVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setVisible(false)}>取消</Button>,
          <Button
            key="ok"
            type="primary"
            style={{marginLeft: 10}}
            htmlType="submit"
            onClick={() => {
              form.validateFields().then(fields => {
                editApi({ poolId: itemPrice?.poolId, partCnt: fields.cnt}).then(res => {
                  setVisible(false);
                  message.success("操作成功");
                  setParams({}, true);
                  }).catch(e => {
                    message.error(e.message);
                    setVisible(false);
                  });
                });
              }}
          >保存
          </Button>
        ]}
      >
        <Form
          form={form}
          labelCol={{span: 7}}
          wrapperCol={{span: 10}}
        >
          <Item
            label="配件采购数量"
            name="cnt"
            rules={[
              {required: true},
              () => ({
                validator(_, value) {
                  if (value > 0) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('配件采购数量不能低于0'));
                },
              }),
            ]}
          >
            <Input placeholder="请输入配件采购数量" />
          </Item>
        </Form>
      </Modal>
    </div>
  );
}
