import React, { useEffect, useState } from "react";
import { Modal, Skeleton, Table, Select, Form, Input, Divider, Popconfirm, InputNumber, Button, message } from "antd";
import useInitial from "@/hooks/useInitail";
import { PlusOutlined } from "@ant-design/icons";
import { fetchComps, getshoplist } from "../../api";
import st from "../../style.less";
import { edit } from "@/pages/ware/Spu/SkuManage/api";

interface Props{
    onChange?:(data:BearCostSetting.TableList[])=>void;
    value?: BearCostSetting.TableList[];
}

const { Column } = Table;

const ShareRateItemlist = ({onChange, value=[]}:Props) => {
    const typeList = [{id: 1, name: '门店'}, {id: 2, name: '往来单位'}];
    const [form] = Form.useForm();
    const [data, setData] = useState<BearCostSetting.Data>({});
    const [item, setItem] = useState<BearCostSetting.Item>({});
    const [tableList, setTableList] = useState<BearCostSetting.TableList[]>([]);
    const [compsList, setCompsList] = useState<BearCostSetting.Comp[]>([] as BearCostSetting.Comp[]);
    const [shoplist, setShoplist] = useState<BearCostSetting.Shop[]>([]);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        if (!data.type) return;
            fetchComps()
            .then(res => {
                res.data && setCompsList([...res.data]);
            })
            .catch(err => {
                message.error("操作失败");
            });
            getshoplist()
            .then(res => {
                res.data && setShoplist([...res.data]);
            })
            .catch(err => {
                message.error("操作失败");
            });
    }, [data.type]);

    /**
     * @description: 关闭Modal
     * @param {*}
     * @return {*}
     */
    const closeModal = () => {
        setVisible(false);
        form.resetFields();
    };

    /**
     * @description: 编辑
     * @param {BearCostSetting} item
     * @return {*}
     */
    const edit = (item:BearCostSetting.TableList) => {
        const {type, shareRate, id, name, key} = item;
        console.log('type-->', type);
        const shopname = typeList.filter(i => i.id === type)[0].name;
        // if (type === 1) {
        //     const _shoplist = shoplist.filter(i => i.id !== id);
        //     setShoplist([..._shoplist]);
        // } else if (type === 2) {
        //     const _compsList = compsList.filter(i => i.id !== id);
        //     setCompsList([..._compsList]);
        // }
        setData({...data, type});
        form.setFieldsValue({
            type: {value: type, label: shopname},
            id: {value: id, label: name},
            shareRate,
            key
        });
    };

    const _delete = (row:BearCostSetting.TableList) => {
        const { key} =row;
        const _tableList = tableList.filter(i => i.key !== key);
        onChange && onChange?.([..._tableList]);
        // value = [];
        setTableList([..._tableList]);
    };

        /**
     * @description: 分摊form
     * @param {any} feildValue
     * @return {*}
     */
    function handleItemSave(feildValue: any) {
        console.log('feildValue-->', feildValue);
        const {id, type, shareRate, key} = feildValue;
        const _tableList = tableList.filter(i => {
            return i?.key !== key;
        });
        // const _total = tableList.reduce((total, item) => {
        //     if (item.shareRate)total += item.shareRate;
        //     return total;
        // }, 0);
        // if (_total + shareRate >100) {
        //     message.error("分摊比例大于100%");
        //     return;
        // }
        const tableItem = {id: id.value, type: type.value, name: id.label, shareRate, key: _tableList.length +1};
        onChange && onChange?.([..._tableList, tableItem]);
        setTableList([..._tableList, tableItem]);
        closeModal();
    }

    return (
      <>
        <div className={st.header} style={{ display: "flex", justifyContent: "flex-end", marginBottom: 15}}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
                    setVisible(true);
                }}
          >
            新增
          </Button>
        </div>
        <Table
          dataSource={tableList}
          rowKey={(item, index) => `${index}`}
          size="small"  
        >
          <Column 
            title="门店/往来单位"
            dataIndex="name"
            width={200}
            render={(t) => t || "-"}
          />
          <Column 
            title="分摊比例"
            dataIndex="shareRate"
            width={200}
            render={(t) => (t && `${t}%`) || "-"}
          />
          <Column 
            title="操作"
            width={100} 
            dataIndex="unit"
            render={(text, row:BearCostSetting.Item, index) => (
              <span>
                <a
                  onClick={() => {
                    console.log('index', index);
                    edit(row);
                      setVisible(true);
                    }}
                >
                  编辑
                </a>
                <Divider type="vertical" />
                <Popconfirm title="是否删除?" onConfirm={() => _delete(row)} okText="确定" cancelText="取消">
                  <a
                    onClick={(e) => {
                            e.preventDefault();
                        }}
                    style={{ color: "red" }}
                  >
                    删除
                  </a>
                </Popconfirm>
              </span>
                )}
          /> 
        </Table>
              
        <Modal
          title="新增分摊比例"
          visible={visible}
          onCancel={closeModal}
          onOk={form.submit}
        >
          <Form form={form} labelCol={{span: '4'}} onFinish={handleItemSave}>
            <Form.Item
              label="对象类型:"
              name="type"
              rules={[{ required: true, message: '请选择缴费方式' }]}
            >
              <Select
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                labelInValue
                onSelect={(item:any) => {
                    form.resetFields(['id']);
                    setData({...data, type: item.value});
                }}
                filterOption={(input, option: any) => option?.children.indexOf(input) >= 0}
              >
                {
                    typeList && typeList.map((item:any) => (
                      <Select.Option value={item.id} key={item.id}>
                        {item.name}
                      </Select.Option>
                    ))
                }
              </Select>
            </Form.Item>
            <Form.Item
              label={data?.type === 1 ? '门店': "往来单位"}
              name="id"
              rules={[{ required: true, message: '请选择缴费方式' }]}
            >
              <Select
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                labelInValue
                allowClear
                filterOption={(input, option: any) => option?.children.indexOf(input) >= 0}
              >
                {
                    data?.type === 2 && (

                        compsList && compsList.map((item:any) => (
                          <Select.Option value={item.id} key={item.id}>
                            {item.name}
                          </Select.Option>
                        ))
                    )
                }
                {
                    data?.type === 1 && (
                        shoplist && shoplist.map((item:any) => (
                          <Select.Option value={item.id} key={item.id}>
                            {item.name}
                          </Select.Option>
                        ))
                    )
                }
              </Select>
            </Form.Item>
            <Form.Item
              label="分摊比例"
              name="shareRate"
              rules={[{ required: true, message: '请输入缴费标识' }]}
            >
              <InputNumber placeholder="请填写" addonAfter="%" max={100} min={0} precision={2} />
            </Form.Item>
            <Form.Item
              name="key"
            />
          </Form>
        </Modal>
      </>
    );
};

export default ShareRateItemlist;